0%

VueJS: How to listen to child component lifecycle event

VueJS is using similar structure like EventEmitter for child-to-parent communication with its $emit API. When parent component wants to know certain lifecycle events that child component is in, we can simply trigger an event in related hook:


const Child = {
mounted () {
this.$emit('child-mounted')
}
}

<parent @child-mounted="doSomething"><child /></parent>

With that callback, we can do numerous things like managing auto-focus behavior or getting child component layout sizing (width, height etc.).

However, if the child component is from 3rd party library which does not provide such callback, we can still tap into its lifecycle in this way:

<parent @hook:mounted="doSomething">
<child />
</parent>

Strangely, this is not listed in any of the official document. If you are interested, check the source code

So literally it is just syntax-sugar and will trigger event in this special hook: namespace.