Vue的生命周期包含了8个钩子函数:
<body>
<div id="app">
<h2>当前n的值是{{n}}</h2>
<button @click="up">点我n+1</button>
<button @click="des">点击结束</button>
</div>
<script src="js/vue.js"></script>
<script>
Vue.config.productionTip=false;
new Vue({
el:'#app',
data(){
return{
n:1
}
},
methods:{
up(){
this.n++;
},
des(){
this.$destroy();
}
},
beforeCreate() {
console.log("beforeCreate");
}, created() {
console.log("created");
}, beforeMount() {
console.log("beforeMount");
}, mounted() {
console.log("mounted");
}, beforeUpdate() {
console.log("beforeUpdate",this.n);
},updated(){
console.log("updated",this.n);
},beforeDestroy(){
console.log("beforeDestroy",this.n);
},destroyed(){
console.log("destroyed",this.n);
}
});
</script>
</body>
刚进入页面,控制台上输出:
beforeCreate
created
beforeMount
mounted
从结果可以看出前四个钩子函数被执行了,而且也可以发现它的一个执行顺序。
继续,当我们点击改变n的值的时候,控制台会输出:
beforeUpdate 2
updated 2
beforeUpdate 3
updated 3
beforeUpdate 4
updated 4
beforeUpdate 5
updated 5
beforeUpdate和updated会随着改变事件一起被执行,并且也有固定的顺序,此时前四个钩子函数没有执行了。
继续,我们点击销毁实例,控制台会输出:
beforeDestroy 5
destroyed 5
当我们点击了销毁后,最后两个钩子函数按照他的顺序被执行,并且执行完成之后,更改n的事件不再有效果,控制台不会再打印任何结果。