每个 Vue 实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会。下面将讲述不同实例被创建的过程:
1.beforeCreate
beforeCreate: function () {
console.log("beforeCreate");
}
2.created
created: function () {
console.log("created");
}
3.beforeMount
beforeMount: function () {
console.log(this.$el);
console.log("beforeMount");//执行的时候页面还没有被渲染
}
4.mounted
mounted: function () {
console.log(this.$el);
console.log("mounted");//页面已经被渲染
}
5.beforeDestory
beforeDestory: function () {
console.log("beforeDestory");
}
6.destroyed
destroyed: function () {
console.log("destroyed");
}
到这里我们会发现,控制台并没有输出beforeDestory和destroyed实例,我们需要在控制台输入vm.$destroy()才能把它们两个“召唤”出来。
7.beforeUpdate
beforeUpdate: function () {
console.log("befroeUpdate");
}
8.updated
updated: function () {
console.log("update");
}
同样,在这里我们看不出有什么变化,这时我们需要定义一个数据,然后在控制台去修改,就可以看到这两个实例被执行了。
data:{
test: "hello world"
}
以上就是我对Vue实例生命周期钩子的一点小总结。