Search⌘ K
AI Features

Activation/Deactivation Related Hooks

Explore how Vue's activated and deactivated lifecycle hooks work with keep-alive components. Understand their timing, use cases, and how they can replace common mounting and destruction hooks. This lesson helps you manage component state efficiently, especially in single-page applications, and optimize resource usage by attaching and detaching resources like listeners and intervals effectively.

Not only can a component be mounted or unmounted, when wrapped in <keep-alive>, it also offers the activated and deactivated hooks. This lesson will only study the hooks, not the <keep-alive> component itself.

Adding the hooks

We can add these hooks in the same way as any other hook.

Javascript (babel-node)
import { createApp } from 'vue'
createApp({
el: '#app',
// data() { ... },
// computed: ...,
// methods: ...,
activated() {
console.log('Hello from activated in app')
},
deactivated() {
console.log('Hello from deactivated in app')
}
})

We can also add these hooks in a single-file component, as shown below:

HTML
<template>
<!-- ... -->
</template>
<script>
export default {
activated() {
console.log('Hello from activated in component')
},
deactivated() {
console.log('Hello from deactivated in component')
}
}
</script>

Understanding the activation and deactivation timing

A component is considered activated as soon as it’s mounted and all its children are activated. A component is kept alive from there on until its parent is destroyed. If something would lead to the destruction of the ...