一、生命周期简介
每个
Vue
实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到DOM
并在数据变化时更新DOM
等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会。
- 生命周期图:
二、钩子函数
beforeCreate()
:表示实例完全被创建出来之前会执行它。此时data()和methods()中的数据和方法都还没有被初始化,在这里是获取不到data()中的数据的,所以console会报错undefined。
created()
: data()和methods(),都已经被初始好了。所以如果要调用 methods() 中的方法,或者操作data()中的数据, 最早只能在created 中操作。
beforeMount()
:表示模板已经在内存中编译完成了,但是尚未把数据模板渲染到页面,如果这个时候想获取页面中的元素只能获取到未编译的值。
mounted()
:表示内存中的模板,已经真实地挂载到了页面中,用户已经可以看到渲染好的页面了。是实例创建期间的最后一个生命周期。当执行完mounted 就表示,实例已经被完全创建好了, 此时, 如果没有其他操作的话,这个实例就存在于内存之中。
beforeUpdate()
:当执行了beforeUpdate 的时候,页面中显示的数据还是旧的,此时data()中的数据是最新的,页面尚未和最新的数据保持同步。
updated()
:updated 事件执行的时候, 页面和data中的数据已经保持同步了,都是最新的。
beforeDestroy()
:销毁之前。
destroyed()
:已经完成销毁。
三、代码示例
<body>
<div id="app">
<span id="num">{{num}}</span>
<button v-on:click="num++">赞!</button>
<h2>{{name}},非常帅!!!有{{num}}个人点赞。</h2>
</div>
<script>
var app = new Vue({
el: "#app",
data: {
name: "jan",
num: 0
},
methods: {
showName() {
return this.name;
},
add() {
this.num++;
}
},
// beforeCreated:该函数就是在 Vue 实例化时 用,也可以将他理解为初始化函数比较方便一点在 Vue1.0 时,这个函数的名字就是 init。
beforeCreate() {
console.log("=========beforeCreate=============");
console.log("数据模型未加载:" + this.name, this.num);
console.log("方法未加载:" + this.showName());
console.log("html 模板未加载: " + document.getElementById("num"));
},
// created:在创建实例之后进行调用。
created: function () {
console.log("=========created=============");
console.log("数据模型已加载:" + this.name, this.num);
console.log("方法已加载:" + this.showName());
console.log("html 模板已加载: " + document.getElementById("num"));
console.log("html 模板未渲染: " + document.getElementById("num").innerText);
},
// beforeMount:页面加载完成,没有渲染。如:此时页面还是{{name}}。
beforeMount() {
console.log("=========beforeMount=============");
console.log("html 模板未渲染: " + document.getElementById("num").innerText);
},
// mounted:功能就是在 dom 文档渲染完毕之后将要执行的函数,该函数在 Vue1.0 版本中名字为 compiled。 此时页面中的{{name}}已被渲染成jan。
mounted() {
console.log("=========mounted=============");
console.log("html 模板已渲染: " + document.getElementById("num").innerText);
},
// beforeUpdate:组件更新之前。
beforeUpdate() {
console.log("=========beforeUpdate=============");
console.log("数据模型已更新:" + this.num);
console.log("html 模板未更新: " + document.getElementById("num").innerText);
},
// updated:组件更新之后。
updated() {
console.log("=========updated============="); console.log("数据模型已更新:" + this.num);
console.log("html 模板已更新: " + document.getElementById("num").innerText);
}
});
</script>
</body>
四、渲染过程展示
五、结束语
“-------怕什么真理无穷,进一寸有一寸的欢喜。”
微信公众号搜索:饺子泡牛奶。