5

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.

7
  • 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. Commented Nov 30, 2018 at 4:22
  • i am updating parentData by calling init() in methods from mounted.added this code in top. Commented Nov 30, 2018 at 4:44
  • Did you realize you should <child-component :parent-data="parentData">? your child component has a prop parentData not data. Commented Nov 30, 2018 at 4:46
  • 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. Commented Nov 30, 2018 at 5:08
  • can you please share plunkr link for this? Commented Nov 30, 2018 at 5:10

1 Answer 1

5

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.