beforeDestroy钩子函数
- 场景:在实例销毁之前调用。此时实例仍然完全可用,可用于解绑自定义事件监听器、取消定时器等操作,因为此时组件实例还存在,能正常访问组件的属性和方法。
- 举例:
<template>
<div>
<button @click="startTimer">开始定时器</button>
</div>
</template>
<script>
export default {
data() {
return {
timer: null
};
},
methods: {
startTimer() {
this.timer = setInterval(() => {
console.log('定时器在运行');
}, 1000);
}
},
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer);
console.log('定时器在beforeDestroy中被清除');
}
}
};
</script>
destroyed钩子函数
- 场景:在实例销毁后调用。此时,所有的指令都被解绑,所有的事件监听器被移除,子实例也都被销毁。通常用于一些需要在组件完全销毁后执行的操作,比如打印日志记录组件已销毁等。
- 举例:
<template>
<div>
<p>这是一个示例组件</p>
</div>
</template>
<script>
export default {
destroyed() {
console.log('组件已销毁,此日志记录在destroyed钩子中');
}
};
</script>