首先上一个vue官方文档上演示vue生命周期的图片
在整个生命周期中,vue有多个钩子函数,不同钩子函数在vue生命周期的不同时刻执行,下面列出钩子函数:
* beforeCreate
* created
* beforeMount
* mounted
* beforeUpdate
* updated
* beforeDestroy
* destroyed
如同官方文档原话,“你不需要立马弄明白所有的东西,不过随着你的不断学习和使用,它的参考价值会越来越高”,在经过实践过后,下面总结一下我对生命周期不同阶段的理解
下面是一段用于演示的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
</head>
<body>
<div id="app">
<h1>{{ message }}</h1>
</div>
</body>
<script>
var vm = new Vue({
el: '#app',
data: {
message: 'the lifecycle of Vue'
},
beforeCreate: function() {
console.group('------beforeCreate------');
console.log("%c%s", "color:red" , "el : " + this.$el); //undefined
console.log("%c%s", "color:red","data : " + this.$data); //undefined
console.log("%c%s", "color:red","message: " + this.message)
},
created: function() {
console.group('------created------');
console.log("%c%s", "color:red","el : " + this.$el); //undefined
console.log("%c%s", "color:red","data : " + this.$data); //已被初始化
console.log("%c%s", "color:red","message: " + this.message); //已被初始化
},
beforeMount: function() {
console.group('------beforeMount------');
console.log("%c%s", "color:red","el : " + (this.$el)); //已被初始化
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data); //已被初始化
console.log("%c%s", "color:red","message: " + this.message); //已被初始化
},
mounted: function() {
console.group('------mounted------');
console.log("%c%s", "color:red","el : " + this.$el); //已被初始化
console.log(this.$el);
console.log("%c%s", "color:red","data : " + this.$data); //已被初始化
console.log("%c%s", "color:red","message: " + this.message); //已被初始化
}
})
</script>
</html>
在浏览器中运行上面的代码,打开控制台显示的结果如下:
beforeCreate 和 created之间的生命周期
在这个阶段中,进行事件的初始化以及数据的观测,执行完created后,数据已经进行了绑定,但此时 el 还是 undefined
created 和 beforeMount之间的生命周期
在这个阶段中会判断有没有 el 选项,如果有继续编译下面的阶段,如果没有则停止编译
尝试注释掉上述代码中的该行
el: '#app',
重新编译运行,结果如下:
我们发现在执行完 created 函数之后就停止了
手动在控制台执行
vm.$mount('#app')
结果如下:
可以看出 el 选项是在beforeMount 函数中绑定的
beforeMount 和 mount 之间的生命周期
注意下面的截图:
可以看到在mouned之前,h1中只是通过{{ message }}进行占位,还没有将具体数据挂载到页面上,mounted 执行后具体数据才真正挂载到页面上
beforeUpdate 和 updated 之间的生命周期
在beforeUpdate中,可以监听到data的变化但是view层没有被重新渲染,view层的数据没有改变
在updated中,view层重新渲染,数据更新
以上是对于vue生命周期的一些理解,如有错误欢迎指正