我有一个带有以下行的父组件
<router-view :product-id="productId" :data-source="attributes"></router-view>
根据上下文,它呈现路由器配置中定义的两个组件之一
path: 'parent',
component: Parent,
children:
[
    {
        path: 'edit',
        component: Edit,
        children:
        [
            {
                path: 'attribute/:id',
                component: Attribute,
            }
        ]
    },
    {
        path: 'grid',
        component: Grid,
    }
]
问题是 product-id 和 data-source props 仅在 Edit 和 Grid 组件中可用。我想让它们在 Attribute 组件中可用,而 Edit 组件只是带有一些静态文本的背景(许多组件很常见)。
作为一种解决方法,我在向下传递对象的 Edit 组件中创建了一个 propertyBag 道具。这就是我在父组件中使用它的方式
 <router-view :property-bag="{ productId:productId, dataSource:dataSource, ...
和编辑组件
<router-view :property-bag="propertyBag"></router-view>
有没有更简单的方法来实现它?
Vue $attrs 是传播 props 的新方式
从文档:
vm.$attrs
包含未被识别(和提取)为 props 的父范围属性绑定(类和样式除外)。当一个组件没有任何声明的 props 时,它本质上包含所有父级范围的绑定(类和样式除外),并且可以通过
v-bind="$attrs"- 在创建高阶组件时有用传递给内部组件。
有关更多信息,请参阅Vue.js API 参考 - $attrs
| 归档时间: | 
 | 
| 查看次数: | 8252 次 | 
| 最近记录: |