一、定义:
vue生命周期钩子 : vue从初始化到销毁的过程中会执行的函数
二、生命周期总的分为四个阶段8个钩子 :
(1)初始化阶段: beforeCreate、 created
(2)挂载阶段 : beforeMount、mounted
(3)更新阶段 : beforeUpdate、updated
(4)销毁阶段: beforeDestroy、destroyed
三、举例观察:
父组件:
<template>
<div>
<LifeCycle></LifeCycle>
</div>
</template>
<script>
import LifeCycle from "@/components/LifeCycle.vue";
export default {
components:{
LifeCycle
},
data(){
return{}
}
}
</script>
<style>
</style>
子组件:
<template>
<div>
<button @click=" name='李四' ">点我改名字</button>
<button @click="$destroy()">点我销毁</button>
<p>{{ name }}</p>
<p>{{ age }}</p>
</div>
</template>
<script>
export default {
data() {
return {
name: "张三",
age: 20
};
},
methods: {},
/* 生命周期钩子 */
// 1. beforeCreate() : 创建了vue实例(内置事件),但是还没有创建data
beforeCreate() {
console.log(1);
console.log(this);
console.log(this.name)//undefined
},
// 2.created() : 创建了data,但是还没有挂载点
/* 常用: 最早可以获取data的钩子, 一般在这个钩子发送ajax */
created() {
console.log(2);
console.log(this);
console.log(this.$el);//张三
console.log(this.name);//undefined
},
// 3.beforeMount() : 创建挂载点,但是还没有把data挂载到el
beforeMount() {
console.log(3);
console.log(this);
// html环境,这个钩子$el可以获取挂载点。 脚手架环境, 这个钩子$el获取的是undefined
console.log(this.$el);
const p = document.querySelector("p");
console.log(p); //null 没有渲染,所以无法获取dom
},
// 4.mounted() : 完成初始渲染。 把data数据渲染到挂载点el(完成初始渲染)
/* 常用: 最早可以操作DOM的钩子 */
mounted() {
console.log(4);
console.log(this);
console.log(this.$el);
const p = document.querySelector("p");
console.log(p); // p标签 完成渲染
},
// 5.beforeUpdate() : 检测到data数据发生变化,但是还没有更新el(页面还没有更新)
beforeUpdate() {
console.log(5);
console.log(this);// 获取的是变化后的数据, 但是页面还是显示之前的数据
},
// 6.updated(): 更新之后的data,完成渲染
updated() {
console.log(6);
console.log(this);
},
// 7.beforeDestroy(): 正在销毁(接触data与el绑定、移除事件监听、移除侦听器)
/*触发销毁钩子的两个条件
(1)对组件使用v-if
(2)调用组件的 this.$destroy()
*/
beforeDestroy() {
/*
解除侦听器、事件监听等
一般在这里清除永久定时器 clearInterval()
*/
console.log(7);
console.log(this);
},
//8.destroyed(): vue实例完成销毁
destroyed() {
console.log(8);
console.log(this);
}
};
</script>
<style>
</style>
想要跟细致的观察变化,可以在每个钩子里面的最后一行打上断点(效果图)