章节目录:
一、生命周期简介
- 生命周期图:
二、钩子函数
三、代码示例
<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>