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

How to test Web Workers with Jest

Do you know the best part of Web Workers? They can speed up heavy tasks on your UI. But, have you tried testing them? Is not that easy... until now.

Andrea Stagi

Andrea Stagi

Oct 20, 2020

How to use the new Fetch in Nuxt.js

The Nuxt team is on fire, releasing new stuff every week! In this tip Samuel shows you a feature that might've gone unnoticed... till now.

Samuel Snopko

Samuel Snopko

Sep 7, 2020

Sponsors

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

Silver
Learning Partner