本文主要介绍Vue.js中实例创建到销毁的整个生命周期,通过下面这个小案例进行演示。
Vue实例默认会先执行四个函数,分别是创建前、已创建、挂载前和已挂载函数。当点击案例中的第一个按钮时,数据会发生变化,更新前及已更新对应的函数会被执行。当点击案例中的第二个按钮时,Vue实例被销毁,销毁前及已销毁对应的函数会被执行
具体说明:(通过debugger打断点更易理解)
beforeCreate会在实例data等创建前进行调用,此时访问data中的数据,会是undefined。created会在数据创建后执行,可以访问data中的数据,此时数据还未被渲染至页面上。beforeMount在挂载前执行,此时可对data中的数据作最后一次修改。mounted在数据挂载之后执行.当更新数据时,beforeUpdate会先执行,此时更新的数据还未被渲染至页面上。updated在数据更新完成后执行,此时页面已渲染了最新的数据。删除实例时,会先执行beforeDestroyed,此时方法和数据都未删除。destroyed在删除之后执行,此时方法等失效,但数据可以访问。
效果如图:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<div v-text="msg"></div>
<div><button @click="update">点击更新</button></div>
<div><button @click="destroy">点击销毁</button></div>
</div>
<script src="./vue.min.js"></script>
<script>
let vu = new Vue({
el: '#app',
data: {
msg: 'default'
},
methods: {
update: function() {
this.msg = 'changed'
},
destroy: function() {
this.$destroy();
}
},
beforeCreate: function() {
console.log('创建前');
},
created: function() {
console.log('已创建');
},
beforeMount: function() {
console.log('挂载前');
},
mounted: function() {
console.log('已挂载');
},
beforeUpdate: function() {
console.log('更新前');
},
updated: function() {
console.log('已更新');
},
beforeDestroy: function() {
console.log('销毁前');
},
destroyed: function() {
console.log('已销毁');
}
})
</script>
</body>
</html>