vue中的生命周期(三)-销毁

本文探讨了Vue中组件的销毁过程,包括beforeDestroy和destroyed两个生命周期钩子的使用,用于执行清理任务,如关闭计时器和删除第三方实例。讨论了两种销毁方式:通过外部开关销毁(同时销毁DOM结构)和内部调用$destroy方法(仅销毁组件本身,不涉及DOM)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

销毁

触发条件: 当组件销毁时
beforeDestroy
destroyed

这两个钩子功能一致的,这两个钩子没有太大的区别
作用:
用来做善后的,比如计时器的关闭 第三方实例的删除

1. 通过开关的形式 - 外部销毁

<div id="app">
<button @click = "flag = !flag"> 切换 </button>
<Hello v-if = "flag"></Hello>
</div>
<template id="hello">
<div>
hello
</div>
</template>

Vue.component('Hello',{
template: '#hello',
mounted () {
this.time = setInterval ( () => {
console.log( 'aaaa' )
},1000)
},
beforeDestroy () {
console.log('beforeDestroy')
clearInterval( this.time )
},
destroyed () {
console.log('destroyed')
}
})
new Vue({
el: '#app',
data: {
flag: true
}
})


2. 通过调用 $destroy 方法 - 内部销毁

<div id="app">
<Hello></Hello>
</div>
<template id="hello">
<div class="hello-box">
<button @click = "clear"> 销毁 </button>
hello
</div>
</template>

Vue.component('Hello',{
template: '#hello',
methods: {
clear () {
this.$destroy()
}
},
mounted () {
this.time = setInterval ( () => {
console.log( 'aaaa'' )
},1000)
},
beforeDestroy () {
console.log('beforeDestroy')
clearInterval( this.time )
document.querySelector('.hello-box').remove()
},
destroyed () {
console.log('destroyed')
}
})
new Vue({
el: '#app',
data: {
flag: true
}
})

对比: 内部销毁 vs 外部销毁
外部销毁不仅能销毁组件,也能销毁该组件的dom结构
内部销毁只能销毁组件,不能销毁组件的dom结构

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值