[Vuejs]-Change value of a props in beforeDestroy/Destroyed cycle of child component does not work

0👍

Don’t change the value of the prop. Have the component emit an event so that the parent can take the appropriate action.

Below is an example of a component that is created when the checkbox is checked, and is destroyed when it gets unchecked. The component emits a "dying" event, and the parent receives it and prints a scream to the console.

new Vue({
  el: '#app',
  data: {
    showIt: true
  },
  methods: {
    scream() {
      console.log("Aaarg!");
    }
  },
  components: {
    myComponent: {
      beforeDestroy: function() {
        this.$emit('dying');
      }
    }
  }
});
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <input type="checkbox" v-model="showIt">
  <my-component v-if="showIt" hasload="true" @dying="scream" inline-template>
    <div>Here I am</div>
  </my-component>
</div>
👤Roy J

0👍

I assume you’re trying to communicate to the parent that the child has loaded. In that case, you can pass a function as a prop and simply call it when the child mounts.

Parent HTML:

<child :my-load-fn="loadFn"></child>

Parent JS:

methods: {
  loadFn() {
    this.childHasLoaded = true
  }
}

Child JS:

props: ['myLoadFn'],
mounted() {
  this.myLoadFn()
}
👤Tyler

Leave a comment