生命周期
创建阶段
- -> beforeCreate 初始化事件和生命周期
- beforeCreate -> created 数据观测、属性、侦听器配置等
- created -> beforeMount 模板编译到render
- render
- mounted 异步请求、操作DOM、定时器等
- 在mounted之后,vue并不承诺子组件的DOM已挂载完成,可以使用this.$nextTick()回调函数
更新阶段
- -> beforeUpdate 依赖数据改变或$forceUpdate强制刷新
- beforeUpdate 移除已经添加的事件监听器等(万万不可更改依赖数据,会出现死循环)
- render
- updated 操作DOM添加事件监听器等(万万不可更改依赖数据,会出现死循环)
- 在updated之后,vue并不承诺子组件的DOM已挂载完成,可以使用this.$nextTick()回调函数
销毁阶段
- beforeDestory 移除已经添加的事件监听器、计时器等
- destroyed
- 在destroyed之后,vue并不承诺子组件的DOM已挂载完成,可以使用this.$nextTick()回调函数
创建阶段和销毁阶段在组件的生命周期中只会执行一次,更新阶段会执行多次
<template>
<div>
{{ log("render") }}
{{ now }}
<button @click="start = !start">{{ start ? "停止" : "开始" }}</button>
</div>
</template>
<script>
import moment from "moment";
export default {
data: function() {
console.log("data");
this.moment = moment;
this.log = window.console.log;
return {
now: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
start: false
};
},
watch: {
start() {
this.startClock();
}
},
beforeCreate() {
console.log("beforeCreate");
},
created() {
console.log("created");
},
beforeMount() {
console.log("beforeMount");
},
mounted() {
console.log("mounted");
this.startClock();
},
beforeUpdate() {
console.log("beforeUpdate");
},
updated() {
console.log("updated");
},
beforeDestroy() {
console.log("beforeDestroy");
clearInterval(this.clockInterval);
},
destroyed() {
console.log("destroyed");
},
methods: {
startClock() {
clearInterval(this.clockInterval);
if (this.start) {
this.clockInterval = setInterval(() => {
this.now = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
}, 1000);
}
}
}
};
</script>