[Vuejs]-How to execute action in child component after parent update

0👍

After some experimenting I found that passing a callback to the parent works best for my purpose. The child wraps the data, and a callback in an event which is then received by the parent. The parent can execute the callback in context of the child, after it is finished. I also found it has the added benefit of allowing multiple child components to be rendered in a loop. While this wasn’t a requirement on my original question, it is certainly nice to have.

Vue.component('child-component', {
  data: function() {
    return {
      id: this.childId,
      value: 'Hello World'
    };
  },
  props: ['childId'],
  methods: {
    saveData(){
      data = {
        id: this.id,
        value: this.value
      };
      callback = () => {alert('CHILD COMPONENT SAYS: Initial Value of Child ' + this.id  + ' Is: ' + this.value); this.clearData(); alert('CHILD COMPONENT SAYS: Final Value of Child ' + this.id  + ' Is: ' + this.value); };
      this.$emit('saveEvent', {data, callback})
    },
    clearData(){
      this.value = '';
    }
  },
  template: `<div>I Am Child {{ childId }} <button @click="saveData">Click Me To Save My Data</button></div>`
});

const vm = new Vue({
  el: '#app',
  data: {},
  methods: {
    saveData({data, callback}){
      debugger;
      alert('PARENT COMPONENT SAYS: Saving data...');
      callback();
    }
  },
  template: `
    <div>
      <p>I am the parent component</p>
      <child-component v-for="n in 5" :childId="n" :key="n" @saveEvent="saveData($event)" />
    </div>`
})
<html>
   <head>
     <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
    </div>
  </body>
</html>

0👍

Changing the state in the parent will update the state in the child. So, if you update any props, this will be reactive and updated in the children properly.

You could add a watch (to the child component) on the passed props, especially if the given object do have changing data nested deeply thanks to deep: true.

https://v2.vuejs.org/v2/api/#watch

Leave a comment