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

#Vue

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!

Remember you can read this tip online (with copy/pasteable code), and don’t forget to share VueDose with your colleagues, so they also know about these tips as well!

See you next week.

Alex

Do you want to sponsor a VueDose tip? Send an email to info@vuedose.tips and have more info!

Start saving time and get a tip about the Vue ecosystem every week, right in your inbox.