Listen to lifecycle hooks on third-party Vue.js components

Alex Jover Morales

Alex Jover Morales

Mar 17, 2019
1 min read
Share on Twitter or LinkedIn

Here's a very useful tip I learnt once from my friend Damian Dulisz, the Vue.js core team member that created the official Vue newsletter and vue-multiselect.

In some cases I needed to know when a component has been created, mounted or updated from a parent component, specially when building components for vanilla JS libraries.

You've probably already something like that in your own components, for example, by emitting an event in a lifecycle hook from the child component, like this:

mounted() {
  this.$emit("mounted");
}

So then you can listen to it from the parent component like <Child @mounted="doSomething"/>.

Let me tell you this: there is no need for that, and in fact you won't be able to do it on third party components.

Instead, the solution is as simple as listening to an event with the lifecycle hook name, prefixed by @hook:.

For instance, if you want to do something when the third-party component v-runtime-template renders, you can listen to it's updated lifecycle hook:

<v-runtime-template @hook:updated="doSomething" :template="template" />

Still don't trust me? Check it yourself in this CodeSandbox!

Don't miss out anything about Vue, your favourite framework.

Subscribe to receive all the articles we publish in a concise format, perfect for busy devs.

Related Articles

Lazy load images using v-lazy-image Vue.js component

Learn to improve the web performance of your vue.js application

Alex Jover Morales

Alex Jover Morales

Apr 16, 2019

The new Provide and Inject in Vue 3

Getting stuck into the prop drilling? Learn how provide/inject can make your components more flexible and independent in this short tutorial.

Anthony Konstantinidis

Anthony Konstantinidis

Jul 18, 2022

The 101 guide to Script Setup in Vue 3

Don't you know about Script Setup yet? Check out this short article now and learn the nicest way to define a Vue component right now!

Anthony Konstantinidis

Anthony Konstantinidis

Jun 20, 2022

Sponsors

VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.

Silver
Learning Partner