Search code examples
javascripthtmlvue.jsweb-applications

Pass data from parent component to child of child in Vue js


I am deperately searching for a way to pass data from a parent component to a child of the child component. I know I can use props to do this like in this thread Vue JS Pass Data From Parent To Child Of Child Of Child

But I only get it to work for the "next" child component and I get stuck for the second one.

My parent component:

<ResultBar :carbondata="realCarbonValues" />

data() {
return {
    realCarbonValues: {
        slabs: 20,
        beams: 0, 
        columns: 0,
        foundation: 0,
        core: 0
    }
};

My child component:

props: {
    carbondata:Object
},


console.log(this.carbondata.slabs)

Now, I can log the data in the console from by using the child component

But what do I have to do in the next child componet to pass the data correctly?


Solution

  • depending on what you are trying to do you can just pass it directly as prop again.

    Parent:

    <Child :prop-i-wanna-pass-deeply="something" />

    Child:

    <GrandChild :props-i-wanna-pass-deeply-again="propsIWannaPassDeeply" />

    GrandChild:

    <div>{{ propsIWannaPassDeeplyAgain }} is now here</div>


    or just use provide and inject to avoid prop-drilling.

    See: https://v2.vuejs.org/v2/api/#provide-inject

    Read the note about reactivity of provide/inject.

    Parent:

    <Child /> <!-- no need to pass the prop -->
    
    provide() {
      return {
        something: "fooAbc",
      }
    }
    

    Child:

    <GrandChild />

    GrandChild:

    <div>{{ something }}</div>
    
    inject: ['something']