了解 Vue 生命周期
前言
每个 Vue 实例在被创建,创建结束以及更新,更新结束都会经历一系列的过程。在这个过程中,Vue 内部会暴露一些钩子函数(其实也就是回调函数)供开发者使用做其他的事情,这些钩子函数就是Vue 的生命周期。
一、beforeCreate
时间:实例刚在内存被创建出来,此时 data 数据和 methods 方法还没有初始化。不能访问到data、computed、watch、methods上的方法和数据。用于初始化变量。
new Vue({
data: {
index: 1
},
beforeCreate: function () {
//data数据还没有被初始化
console.log(this.index)//undefined
}
})
二、created 函数
时间:在一个实例被创建之后执行。data 数据和 methods 方法已经初始化。未挂载到DOM,不能访问到
ref属性内容为空数组。用于 ajax 请求,页面初始化。
案例:
new Vue({
data: {
index: 1
},
created: function () {
//data数据已经被初始化了
console.log(this.index)//1
}
})
三、beforeMount
时间:完成模板编译,编译成 render 函数,但是还未挂载到真实 DOM 节点上。
<body>
<div id="app">
<div @click="change">{{index}}</div>
</div>
</body>
<script>
new Vue({
data: {
index: 1
},
methods: {
change() {
this.index = 2;
}
},
beforeMount: function () {
//界面渲染之前显示的还是之前的数据,渲染之后不会调用。
console.log(this.index)//1
}
})
</script>
四、mounted
时间:已经将编译好的模板,挂载到 DOM 节点上。可以使用 DOM API,获取真实 DOM 节点;可以访问 $ref;也可用于 ajax 请求。
<body>
<div id="app">
<div @click="change">{{index}}</div>
</div>
</body>
<script>
new Vue({
data: {
index: 1
},
methods: {
change() {
this.index = 2;
}
},
mounted: function () {
var app =document.getElementById("app");
console.log(app);
//界面渲染之前显示的还是之前的数据,渲染之后不会调用。
console.log(this.index)//1
}
})
</script>
五、beforeUpdate
时间:状态更新之前执行,此时 data 中的数据是最新的,但是页面还未进行渲染。可以在更新之前,访问现有的 DOM 元素,比如手动清除事件监听。
<body>
<div id="app">
<div @click="change">{{index}}</div>
</div>
</body>
<script>
new Vue({
data: {
index: 1
},
methods: {
change() {
this.index = 2;
}
},
mounted: function () {
//界面渲染之后才会调用,数据为更新之后的数据。
console.log(this.index)//2
}
})
</script>
六、updated
时间:页面渲染更新完成。避免在这里操作数据,可能陷入死循环。
<body>
<div id="app">
<div @click="change">{{index}}</div>
</div>
</body>
<script>
new Vue({
data: {
index: 1
},
methods: {
change() {
this.index = 2;
}
},
mounted: function () {
//界面渲染之后才会调用,数据为更新之后的数据。
console.log(this.index)//2
}
})
</script>
七、beforeDestroy
时间:实例销毁前调用,这一步仍然可以使用实例。常用于销毁定时器、解绑全局事件、销毁插件对象等操作。
八、destroyed
时间:实例销毁后调用。事件监听器会被消除,子实例也会被销毁。
转载:https://blog.csdn.net/weixin_44135121/article/details/101780192
查看评论