其他vue相关文章可以在我个人分类中的vue.js部分查看
# Vue的声明周期
首先看一下官方给出的声明周期图示
很清晰明了,可以看出整个Vue的声明周期流程是怎样的,但是并没有做出具体的标注,每一个步骤还是缺少详细说明,下面以实例来探究一下。
首先先上源码,有兴趣的同学也可以自己来测试或是添加新的方法进去。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./lib/vue.js"></script>
</head>
<body>
<div id="app">
<h1 id="bh">{{msg}}</h1>
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
msg: "good!"
},
methods: {
hello:function(){
console.log("hello world")
},
updateData:function(){
this.msg="not good!!!"
}
},
beforeCreate: function () {
console.log('beforeCreated----start')
console.log(this.msg)
this.hello()
console.log('beforeCreated----end')
},
created: function () {
console.log('created----start')
console.log(this.msg)
this.hello()
console.log('created----end')
},
beforeMount: function () {
console.log('beforeMount----start')
console.log(document.getElementById('bh').innerText)
console.log('beforeMount----end')
},
mounted: function () {
console.log('mounted----start')
console.log("before update: " + document.getElementById('bh').innerText)
this.updateData()
console.log("after update: " + document.getElementById('bh').innerText)
console.log("msg in data: " + this.msg)
console.log('mounted----end')
},
beforeUpdate: function () {
console.log('beforeUpdate----start')
console.log(document.getElementById('bh').innerText)
console.log("msg in data: " + this.msg)
console.log('beforeUpdate----end')
},
updated: function () {
console.log('updated----start')
console.log(document.getElementById('bh').innerText)
console.log("msg in data: " + this.msg)
console.log('updated----end')
},
beforeDestroy: function () {
console.log('beforeDestroy----start')
console.log('beforeDestroy----end')
},
destroyed: function () {
console.log('destroyed----start')
console.log('destroyed----end')
}
})
</script>
</body>
</html>
# 1. beforeCreate
运行结果:
可以看出,在这一阶段,Vue的data和methods并没有创建好,所以无法对其进行访问。该阶段仅仅完成了一些默认的生命周期函数和默认事件。
# 2. created
运行结果:
可以看到在这一阶段已经可以完成对数据和方法的创建了,所以最早可以进行操作的阶段就在这一个阶段
# 3. beforeMount
运行结果:
此时模板已经编译完成,但是只是储存在内存中,还没有渲染到页面中。此时页面上只有模板字符。
# 4. Mounted
运行结果:
此时的模板已经渲染到页面中,所以数据更新,看到我们希望看到的页面。此时Vue实例全部初始化完毕,可以对DOM进行操作。但是可以看到此时的更新操作并没有产生效果
# 5. beforeUpdate
运行结果:
这里的更新操作依旧没有产生效果
# 6. updated
运行结果:
在该阶段后,更新结果被渲染到页面上。
# 7. beforeDestroy
销毁前,所有的数据、方法、指令、过滤器等等都处于可用状态
# 8. destroyed
完全进行了销毁