vue:将 props 传递给所有后代

Pab*_*blo 2 vue.js

我有一个带有以下行的父组件

<router-view :product-id="productId" :data-source="attributes"></router-view>
Run Code Online (Sandbox Code Playgroud)

根据上下文,它呈现路由器配置中定义的两个组件之一

path: 'parent',
component: Parent,
children:
[
    {
        path: 'edit',
        component: Edit,
        children:
        [
            {
                path: 'attribute/:id',
                component: Attribute,
            }
        ]
    },
    {
        path: 'grid',
        component: Grid,
    }
]
Run Code Online (Sandbox Code Playgroud)

问题是 product-id 和 data-source props 仅在 Edit 和 Grid 组件中可用。我想让它们在 Attribute 组件中可用,而 Edit 组件只是带有一些静态文本的背景(许多组件很常见)。

作为一种解决方法,我在向下传递对象的 Edit 组件中创建了一个 propertyBag 道具。这就是我在父组件中使用它的方式

 <router-view :property-bag="{ productId:productId, dataSource:dataSource, ...
Run Code Online (Sandbox Code Playgroud)

和编辑组件

<router-view :property-bag="propertyBag"></router-view>
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法来实现它?

clo*_*pre 8

Vue $attrs 是传播 props 的新方式

从文档:

vm.$attrs

包含未被识别(和提取)为 props 的父范围属性绑定(类和样式除外)。当一个组件没有任何声明的 props 时,它本质上包含所有父级范围的绑定(类和样式除外),并且可以通过v-bind="$attrs"- 在创建高阶组件时有用传递给内部组件。

有关更多信息,请参阅Vue.js API 参考 - $attrs