什么是生命周期销毁?
在Vue.js中,生命周期的“销毁”阶段指的是组件从页面卸载和Vue实例被销毁的过程。这个阶段是组件生命周期的最后阶段,涉及到清理工作,以确保不会留下内存泄漏或其他资源问题。 vm.$destroy():手动卸载和销毁Vue实例。
卸载/销毁之前:beforeDestroy()
注意!此时,Vue实例仍然完全可用,所有的数据绑定、事件监听器和子Vue实例都仍然是活跃的。
卸载/销毁之之后:destroyed()
注意!此时,所有的数据绑定已经被解除,所有的事件监听器已经被移除,所有的子Vue实例也已经被销毁
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="icon" href="img/network.png" type="image/x-icon">
<script src="js/Vue.js"></script>
<!-- 引入Vue.js文件 -->
</head>
<body>
<div id="root">
<h2>当前的n值是:{{n}}</h2>
<button @click="add">点我n+1</button>
<button @click="bye">点我销毁vm</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false;
//阻止Vue在启动时生成生产提示
new Vue({
el: '#root',
data: {
n: 1
},
methods: {
add() {
console.log('add');
this.n++
},
bye() {
console.log('bye');
this.$destroy()
}
},
watch: {
n() {
console.log('n变了')
}
},
beforeCreate() {
console.log('beforeCreate')
},
created() {
console.log('created')
},
beforeMount() {
console.log('beforeMount')
},
mounted() {
console.log('mounted')
},
beforeUpdate() {
console.log('beforeUpdate')
},
updated() {
console.log('updated')
},
beforeDestroy() {
console.log('beforeDestroy')
},
destroyed() {
console.log('destroyed')
}
})
</script>
</body>
</html>