vue:将 props 传递给所有后代 [英] vue: passing props down to all descendants

查看:42
本文介绍了vue:将 props 传递给所有后代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a parent component with the following line

<router-view :product-id="productId" :data-source="attributes"></router-view>

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

depending on the context it renders one of the two components defined in the router config

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 组件只是带有一些静态文本的背景(许多组件很常见).

The thing is that the product-id and data-source props are available only in the Edit and Grid components. I'd like to have them available in the Attribute component as well as the Edit component is just a background with some static text (common for many components).

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

As a workaround I've created a propertyBag prop in the Edit component that passes an object down. That's the way I use it in the parent component

 <router-view :property-bag="{ productId:productId, dataSource:dataSource, ...

和编辑组件

<router-view :property-bag="propertyBag"></router-view>

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

Is there a simpler way to achieve it ?

推荐答案

你看过 vuex.它确实非常易于使用,并允许您将整个应用程序的数据存储在单个数据存储中.这意味着您不必一直通过 props 传递数据,您只需访问 store 中设置的变量即可.

Have you looked at vuex. It's really quite easy to use and allows you to store data for your entire app in a single data store. This means you don't have to keep passing data through props, you can just access variables set in the store.

这是 vuex 文档的链接(什么是 Vuex)https://vuex.vuejs.org

Here is a link to vuex docs (What is Vuex) https://vuex.vuejs.org

这篇关于vue:将 props 传递给所有后代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆