1.生命周期图
2.生命周期方法
2.1 初始化显示
- beforeCreate()
- created()
- beforeMount()
- mounted()
2.2 更新状态: this.xxx = value
- beforeUpdate()
- updated()
2.3 销毁 vue 实例: vm.$destory()
- beforeDestory()
- destoryed()
常用的生命周期方法:
- created()/mounted(): 发送 ajax 请求, 启动定时器等异步任务
- beforeDestory(): 做收尾工作, 如: 清除定时器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>10-Vue实例的生命周期</title>
</head>
<body>
<div id="app-10">
<button @click="destroyVue">destroy vue</button>
<p v-show="isShowing">{{msg}}</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
const vue = new Vue({
el: '#app-10',
data: {
msg: 'Vue的生命周期测试',
isShowing: true,
persons: []
},
beforeCreate() {
console.log('beforeCreate() msg=' + this.msg)
},
created() {
console.log('created() msg=' + this.msg)
this.intervalId = setInterval(() => {
console.log('定时器,更改数据')
this.isShowing = !this.isShowing
}, 1000)
},
beforeMount() {
console.log('beforeMount() msg=' + this.msg)
},
mounted() {
console.log('mounted() msg=' + this.msg)
},
beforeUpdate() {
console.log('beforeUpdate isShowing=' + this.isShowing)
},
updated() {
console.log('updated isShowing=' + this.isShowing)
},
beforeDestroy() {
console.log('beforeDestroy() msg=' + this.msg)
clearInterval(this.intervalId)
},
destroyed() {
console.log('destroyed() msg=' + this.msg)
},
methods: {
destroyVue() {
vue.$destroy()
}
}
});
</script>
</body>
</html>