Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue: passing props down to all descendants

Tags:

vue.js

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,
    }
]

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).

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, ...

and the Edit component

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

Is there a simpler way to achieve it ?

like image 915
Pablo Gablo Avatar asked Dec 07 '25 06:12

Pablo Gablo


1 Answers

Vue $attrs is the new way to propagate props

From the Docs:

vm.$attrs

Contains parent-scope attribute bindings (except for class and style) that are not recognized (and extracted) as props. When a component doesn’t have any declared props, this essentially contains all parent-scope bindings (except for class and style), and can be passed down to an inner component via v-bind="$attrs" - useful when creating higher-order components.

For more information, see Vue.js API Reference - $attrs

like image 103
cloudpre Avatar answered Dec 12 '25 15:12

cloudpre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!