beforeDestroy与destroyed
这两个钩子处理组件销毁阶段的逻辑。
Vue 2 命名
JavaScript
export default {
beforeDestroy() {
// 组件仍可用
clearInterval(this.timer)
},
destroyed() {
// 组件已销毁
console.log('组件已销毁')
}
}
Vue 3 命名
JavaScript
export default {
beforeUnmount() {
clearInterval(this.timer)
},
unmounted() {
console.log('组件已卸载')
}
}
Composition API
JavaScript
import { onBeforeUnmount, onUnmounted } from 'vue'
export default {
setup() {
const timer = setInterval(() => {
console.log('tick')
}, 1000)
onBeforeUnmount(() => {
clearInterval(timer)
})
onUnmounted(() => {
console.log('清理完成')
})
}
}
典型清理
JavaScript
onUnmounted(() => {
// 清理定时器
clearInterval(timer)
// 移除事件监听
window.removeEventListener('resize', handler)
// 取消订阅
subscription.unsubscribe()
})
要点总结
beforeDestroy/beforeUnmount在销毁前执行destroyed/unmounted在销毁后执行- Vue 3 将命名改为
Unmount系列 - 用于清理定时器、事件监听、订阅等资源
📝 发现内容有误?点击此处直接编辑