Home > Back-end >  Apply all props to grandchild component in Vue
Apply all props to grandchild component in Vue

Time:07-28

Let's say I have a component Parent, a Child and a Grandchild. In Parent, I'm passing the props grandchildParams

In Child, I have something like

<template>
 <p> some extra stuff</p>
 <Grandchild>
</template>

and I'd like to have every prop from grandchildParams being applied in the template to it. For example:

Let's say I have it like { label: 'foo', value: 'bar' } I'd like to have in the Child component the following

<template>
 <p> some extra stuff</p>
 <Grandchild :label='props.label' :value='props.value'>
</template>

But in a way that it works dynamically, without needing to mention label and value or any new value I might add

CodePudding user response:

1- If you are using props, you need to pass data in every component:

Parent

<template>
 <Child :value="myData.value" :label="myData.label"></Child>
</template>

<script>
export default {
  data(){
    return{
     myData:{label:'foo', value:'bar'}
    }
  }
}
</script>

Child

<template>
 <Child :value="value" :label="label"></Child>
</template>

<script>
export default {
  props:['value','label']
}
</script>

Grand Child

<template>
  <p>{{ label }} : {{ value }}</p>
</template>

<script>
export default {
  props:['value','label']
}
</script>

2- Another approach is using provide and inject

Parent

<script>
export default {
 data(){
    return{
     myData:{label:'foo', value:'bar'}
    }
 },
 provide(){
  return{
    myData:this.myData
  }
 }
}
</script>

Grand Child

<template>
  <p>{{ myData.label }} - {{ myData.value }}</p>
</template>

<script>
export default {
  inject:['myData']
}
</script>

CodePudding user response:

Check This one:

Parent

<script>
import Child from "./Child.vue"
export default {
  components:{
    Child
  },
  data(){
    return{
      myData:{label:'Name', value:'John'}
    }
  }
}
</script>

<template>
  <child :pass="myData"></child>
</template>

Child

<template>
  <grand-child v-bind="$props"></grand-child>
</template>

<script>
import GrandChild from "./GrandChild.vue"

export default{
  components:{GrandChild},
  props:['pass']
}
</script>

Grand Child

<template>
  <p>{{ pass.label }}</p>
</template>

<script>
export default {
  props:["pass"]
}
</script>
  • Related