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

Setting up a full static Nuxt site

Overwhelmed by too many options to create a blog? Chill and use Nuxt, Storyblok and TailwindCSS to make it simple, beautiful and incredibly performant

Alex Jover Morales

Alex Jover Morales

Jul 14, 2020

Use Composition API to easily handle API requests in Vue.js

Not sure how to organize your API client in Vue.js? Learn this simple technique on how to do it using the new Composition API and make it easy.

Carlos Rodrigues

Carlos Rodrigues

Jul 6, 2020

Sponsors

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

Silver
StoryBlok
Learning Partner
Vue School