4
votes

Parent component:

<template> 
  <div>
<child-component :data="parentData"></child-component>
  </div>
</template>
<script>
export default {
data() {
return {
parentData: [{info: '123'}, {info: '456'}]
    }
   },methods: {
init() {
  this.parentData = [{info: 'abc'}, {info: 'def'}];
  }
},
mounted() {
this.init();
}
}
</script>

Child component:

<template>
<div>
<span v-for="item in parentData">
{{ item.info }}
</span>
</div>
</template>
<script>
export default {
props: ["parentData"]
}
</script>

Initially i am passing some default data, It is get rendering from parent to child.

But after i am updating data for parentData by calling method (which i need to bypass it with api), child component is not geting updated.

Can anyone please help me how to update props in child component by passing updated data for prop from parent component after rendering the page. Thanks in advance.

1
Do you mean <child-component :parent-data="parentData">? Also you need to share how you are updating parentData so we know why it's not reactive.Psidom
i am updating parentData by calling init() in methods from mounted.added this code in top.Ashok Gurram
Did you realize you should <child-component :parent-data="parentData">? your child component has a prop parentData not data.Psidom
yes thanks my mistake added at here. But in code I added in same way. Because of that at initial it is working but after load sending data is not getting updated.Ashok Gurram
can you please share plunkr link for this?Hardik

1 Answers

5
votes

The child component props should be reactive when the parent data source changes. Here's an example updating the child component every second.

Vue.component('child-component', {
  template:`<div>
<span v-for="item in parentData">
{{ item.info }}
</span>
</div>`,
  props: ['parentData']
})

Vue.component('parent-component', {
  template:`<child-component :parent-data="parentData"></child-component>`,
  data () { 
    return {
      parentData: [{info: '123'}, {info: '456'}]
    }
  },
  mounted () {
    setInterval(() => {
      this.parentData = [
        {
          info: Math.random().toString(36).slice(-3)
        },
        {
          info: Math.random().toString(36).slice(-3)
        }
      ]
    }, 1000)
  }
})

new Vue({
  el: '#app',
  template: '<parent-component></parent-component>'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app"></div>