Vue parent component listens for child component lifecycle

  • 2021-08-10 06:32:46
  • OfStack

For example, if there is a parent component Parent and a child component Child, if the parent component listens to the child component mounting mounted, it will do some logical processing, which can be realized by the following writing:


// Parent.vue
<Child @mounted="doSomething"/>

// Child.vue
mounted() {
 this.$emit("mounted");
}

Above, you need to manually trigger the events of the parent component through $emit. In a simpler way, you can listen through @ hook when the parent component references the child component, as follows:


// Parent.vue
<Child @hook:mounted="doSomething" ></Child>

doSomething() {
  console.log(' The parent component listens to  mounted  Hook function  ...');
},

// Child.vue
mounted(){
  console.log(' Subcomponent trigger  mounted  Hook function  ...');
},  

//  The above output order is: 
//  Subcomponent trigger  mounted  Hook function  ...
//  The parent component listens to  mounted  Hook function  ...

Of course, the @ hook method can not only listen to mounted, but also other life cycle events, such as created, updated, etc.


Related articles: