vue生命周期方法
创建期间:
- beforeCreate:实例刚在内存中创建,还没有初始化好data和methods属性。
- created:实例已经在内存中创建完成,data和methods已经创建完毕。
- beforeMount:模板编译完成,还没有挂载到页面。
- mounted:模板已经挂载到页面中。
运行期间:
- beforeUpdate:实例状态更新前执行,此时data的值已经更新,但页面内容还没有更新。
- updated:实例状态更新完毕后执行,此时data和页面内容都已经更新完毕。
销毁期间:
- beforeDestroy:实例销毁之前执行,此时实例仍完全可用。
- destroyed:此时所有东西已解绑,所有事件监听已移除,所有子实例已销毁。
与keep-alive相关的生命周期方法(以后再说)
- activated:被 keep-alive 缓存的组件激活时调用。
- deactivated:被 keep-alive 缓存的组件停用时调用。
图解
演示
beforeCreate
<body>
<div id="content">
<p id="ppp">{{msg}}</p>
</div>
</body>
<script>
var vm = new Vue({
el:"#content",
data:{
msg:"123"
},
methods:{
hello(){
console.log("hello");
}
},
beforeCreate() {
console.log("beforeCreate...");
console.log(this.msg);
this.hello();
}
});
</script>
执行报错,因为beforeCreate时还没有初始化好data和methods属性。
created
created() {
console.log("create...");
console.log(this.msg);
this.hello();
}
运行,正常打印:
beforeMount
created() {
console.log("create...");
console.log(this.msg);
this.hello();
console.log($("#ppp").html());
},
beforeMount() {
console.log("beforeMount...");
console.log($("#ppp").html());
}
运行,页面内容仍旧是vue未渲染的状态:
mounted
created() {
console.log("create...");
console.log(this.msg);
this.hello();
console.log($("#ppp").html());
},
beforeMount() {
console.log("beforeMount...");
console.log($("#ppp").html());
},
mounted() {
console.log("mounted...");
console.log($("#ppp").html());
}
运行:
beforeUpdate
<body>
<div id="content">
<p id="ppp">{{msg}}</p>
<button v-on:click="changeMsg">改变</button>
</div>
</body>
<script>
var vm = new Vue({
el:"#content",
data:{
msg:"123"
},
methods:{
changeMsg(){
this.msg = "888";
}
},
beforeUpdate() {
console.log("beforeUpdate...");
console.log(this.msg);
console.log($("#ppp").html());
}
});
</script>
运行点击按钮,点击按钮后beforeUpdate方法中msg已经被改变为888,但页面内容的msg依旧是123。
updated
beforeUpdate() {
console.log("beforeUpdate...");
console.log(this.msg);
console.log($("#ppp").html());
},
updated() {
console.log("updated...");
console.log(this.msg);
console.log($("#ppp").html());
}
运行点击按钮,点击按钮,此时msg和页面内容均被改变:
beforeDestroy、destroyed
beforeDestroy应用场景:
- 可能在当前页面中使用了$on方法,那需要在组件销毁前解绑。
- 清除自己定义的定时器
- 解除事件的绑定 scroll mousemove
配合keep-alive:
- 当前路由不使用 缓存,离开当前路由会直接调用 beforeDestroy 和 beforeDestroy 销毁
- 当前路由使用 缓存,离开当前路由不会直接调用 beforeDestroy 和 beforeDestroy 销毁,需要使用路由钩子函数主动的调用:
beforeRouteLeave(to, from, next) {
this.$destroy();
next();
}