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結構

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章