Ashok Gurram
Ashok Gurram

Reputation: 631

Update child component from parent in Vue js

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.

Upvotes: 5

Views: 8206

Answers (1)

Brian Lee
Brian Lee

Reputation: 18197

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>

Upvotes: 5

Related Questions