每个
Vue
实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到DOM
并在数据变化时更新DOM
等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会
生命周期钩子的
this
上下文指向调用它的Vue
实例。不要在选项属性或回调上使用箭头函数,
比如created: () =>console.log(this.a)
或vm.$watch('a', newValue => this.myMethod())
。因为箭头函数并没有 this,this 会作为变量一直向上级词法作用域查找,直至找到为止,经常导致Uncaught TypeError: Cannot read property of undefined
或Uncaught TypeError: this.myMethod is not a function
之类的错误
生命周期图解
<template>
<div id="app">
<div @click="bg+=1"> {{bg}}</div>
<button @click="handleDestroy">销毁</button>
</div>
</template>
<script>
import Vue from 'vue'
export default {
name: "app",
data() {
return {
bg:2020
};
},
methods: {
handleDestroy(){
this.$destroy();
}
},
beforeCreate(){
console.log(this.bg);
console.log("beforecreate--data和methods还未初始化");
},
created(){
console.log(this.bg);
console.log("created--已经初始化好,要操作data和methods数据,最早可以在这里进行");
},
beforeMount(){
console.log(this.bg);
console.log("beforemount--挂载前模板已编译好,但未渲染到页面");
},
mounted() {
console.log(this.bg);
console.log("mounted--已渲染到页面,该函数一执行完,就脱离了创建状态,到运行状态");
},
beforeUpdate(){
console.log(this.bg);
console.log("beforeupdated--页面数据还是旧的");
},
updated(){
console.log(this.bg);
console.log("updated--数据是新的");
},
beforeDestroy() {
this.bg=this.bg+1
console.log(this.bg);
console.log("beforeDestroy--数据销毁");
},
destroyed(){
console.log(this.bg+1);
console.log("Destroy--数据销毁,之后不能再继续操作");
}
}
</script>
<style lang="less" scope>
* {
padding: 0;
margin: 0;
}
#app {
width: 700px;
min-height: 300px;
margin: auto;
.dis {
width: 200px;
height: 100px;
background-color: pink;
}
}
</style>
销毁之后就不能再操作了