组件生命周期的组件钩子之外部/内部销毁
第三步的销毁:beforedestroy / destroyed
销毁方式:最大区别就是第二种无法销毁dom结构
1、通过开关销毁(flag,可以销毁该组件的dom结构)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
</head>
<body>
<div id="app">
<button @click="flag=!flag">切换</button>
<congbo v-if="flag"></congbo>
</div>
<template id="all">
<div>
测试文本
</div>
</template>
</body>
<script>
Vue.component('congbo',{
template:'#all',
mounted(){
this.time=setInterval(function(){
console.log(1999)
},1000)
},
destroyed(){
//destroyed这里处理 相关dom的操作、定时器关闭、第三方实例的删除,主要用来处理善后工作
clearInterval(this.time)
console.log('destroyed')
}
})
new Vue({
el:'#app',
data:{
flag:true
}
})
</script>
</html>
2、通过$destroy()销毁(这种没有销毁掉dom结构,需要相关dom操作再次销毁)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
</head>
<body>
<div id="app">
<congbo></congbo>
</div>
<template id="all">
<div class="box">
<button @click="clear">销毁</button>
测试文本
</div>
</template>
</body>
<script>
Vue.component('congbo',{
template:'#all',
methods: {
clear(){
console.log(this)
this.$destroy()
}
},
mounted(){
this.time=setInterval(function(){
console.log(1999)
},1000)
},
destroyed(){
clearInterval(this.time)
console.log('destroyed')
//操作dom销毁dom结构
document.querySelector('.box').remove()
}
})
new Vue({
el:'#app',
data:{
flag:true
}
})
</script>
</html>