每个 Vue 实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会。
生命周期图示:
1vue对象生命周期
1)初始化显示
* beforeCreate()
* created()
* beforeMount()
* mounted()
2)更新显示:this.xxx=value
* beforeUpdate()
* updated()
3)销毁vue实例:vm.$destroy()
*beforeDestroy()
*destroyed()
2.常用的生命周期方法
created()/mounted(): 发送ajax请求,启动定时器等异步任务
beforeDestroy(): 做收尾工作,如:清除定时器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="test">
<button type="button" @click="destroyVM">destroy vm</button>
<p v-show="isShow">何桥是一只猪</p>
{{isShow}}
</div>
<script type="text/javascript">
new Vue({
el:'#test',
data:{
isShow: false,
},
//1初始阶段
beforeCreate() {
console.log('beforeCreate');
},
created() {
console.log('created');
},
beforeMount() {
console.log('beforeMount');
},
mounted(){//初始化 后立即调用(1c次
console.log('mounted');
this.intervalId = setInterval(() => {//函数作为参数传递,用箭头函数(函数内部没有自己的this))
this.isShow = !this.isShow
}, 1000)
},
//2更新阶段
beforeUpdate() {
console.log('beforeUpdate')
},
updated() {
console.log('updated')
},
//3死亡阶段
beforeDestroy(){//死亡之前调用(1次)
console.log('beforeDeatroy');
//清除定时器
clearInterval(this.intervalId);
},
destroyed() {
console.log('destroyed')
},
methods:{
destroyVM(){
//干掉VM
this.$destroy()
}
}
})
</script>
</body>
</html>
注意:
不要在选项属性或回调上使用箭头函数,比如 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 之类的错误