The onBeforeUnmount Hook
The onBeforeUnmount hook runs a function just before Vue removes a component. onBeforeUnmount is the hook for clean-up work.
Register the hook
The hook logs a goodbye line before the child leaves.
onBeforeUnmount(() => {
console.log('Child is leaving.')
})The child in place
show is true, so the child draws.
<Child v-if="show" />Example
<script setup>
import { ref, defineComponent, onBeforeUnmount } from 'vue'
const Child = defineComponent({
setup() {
onBeforeUnmount(() => {
console.log('Child is leaving.')
})
return {}
},
template: `<p>Child is here.</p>`
})
const show = ref(true)
</script>
<template>
<div>
<button @click="show = !show">Toggle child</button>
<Child v-if="show" />
</div>
</template>
Key points
- onBeforeUnmount takes one function, and Vue calls it before removal.
- Clean-up means undoing work the component started, like stopping a timer.
- The hook runs once, right before the component leaves the page.
- The hook does not run during a static render, so the first output shows the child in place.
- A component removed with v-if runs its onBeforeUnmount hook first.
In this example, Child is a small component with an onBeforeUnmount hook. The hook logs Child is leaving. show is a ref with the value true. The template draws Child while show is true. The button flips show. The first render shows the child in place. A verified variant with show set to false draws no child. The child leaves the page, and its hook runs first.
Note
Import onBeforeUnmount from vue before calling it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is onBeforeUnmount for?