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

销毁

触发条件: 当组件销毁时
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结构

猜你喜欢

转载自blog.csdn.net/A_head_of_cookies/article/details/93892439
今日推荐