生命周期的含义 : 通俗来说,一个组件从创建到销毁的过程就是生命周期.
钩子 : vue从创建到销毁过程中,会执行的一些回调函数
一 . 生命周期钩子分为4个阶段,8个钩子 :
1.初始化阶段 : beforeCreate、 created
2.挂载阶段 : beforeMount、mounted
3.更新阶段 : beforeUpdate、updated
4.销毁阶段 : beforeDestroy、destroyed
二 . 具体执行 :
1. beforeCreate() : 创建了vue实例,但是还没有创建data
2.created() : 创建了data,但是还没有挂载
3.beforeMount() : 创建挂载点,但是还没有把data挂载到el
4.mounted() : 完成初始渲染。 把data数据渲染到挂载点el
5.beforeUpdate() : 检测到data数据发生变化,但是还没有更新el
6.updated(): 更新之后的data,完成渲染
7.beforeDestroy(): 正在销毁(接触data与el绑定、移除事件监听、移除侦听器)
8.destroyed(): 完成销毁
三 . vue初始渲染会执行的4个钩子 :
beforeCreate、 created、 beforeMount、mounted
四 . 三个常用 :
created() : 页面一加载, ajax请求数据渲染页面
mounted() : 最早可以获取页面DOM元素的钩子
beforeDestroy() :
触发场景 : 组件自己v-if为false , 调用组件自己$destroy()方法
应用 : 移除setInterval定时器
五 . 代码演示:
<template>
<div>
<p ref="p">{{name}}</p>
<p >{{age}}</p>
<button @click="age++">点我加一</button>
<button @click="$destroy()">点我销毁</button>
</div>
</template>
<script>
export default {
data(){
return {
name:'佩奇',
age:2
}
},
//1.beforeCreate : 初始化vue实例 但是还没有创建data
beforeCreate(){
// debugger
console.log(1)
console.log(this)
console.log(this.name) //undefined
},
//2.created : 创建了data,但是还没有创建挂载点el
//常用(最早可以操作data的钩子) : 页面加载渲染数据 在这个钩子里面发送Ajax
created(){
// debugger
console.log(2)
console.log(this)
console.log(this.name) //佩奇
},
//3.beforeMount : (vue判断是否创建挂载点,用的哪种方法)创建了el,但是还没有把dom渲染到el上
beforeMount(){
// debugger
console.log(3)
console.log(this)
console.log(this.$el) //undefined
console.log(this.$refs.p) //undefined
},
//4.mounted : (编译模板生成虚拟dom)把data渲染到el上
//常用(完成初始渲染) : 最早可以操作dom
mounted(){
// debugger
console.log(4)
console.log(this)
console.log(this.$el) //div
console.log(this.$refs.p) //p
},
//5.beforeUpdate: 当data数据发生变化,但是还没有更新dom
beforeUpdate(){
console.log(5)
console.log(this)
},
//6.updated: (diff算法对比新旧dom)完成dom更新,判断key值是否一致,比较标签属性类名,完成dom更新后走updated钩子(把变化之后的data渲染到页面)
updated(){
console.log(6)
console.log(this)
},
//beforeDestroy: vue开始渲染,会移除侦听器,子组件,绑定事件等
/*有两种情况可以触发beforeDestroy钩子
(1)组件自己v-if为false
(2)调用组件自己$destroy()方法*/
// 应用:移除setInterval定时器
beforeDestroy(){
debugger
console.log(7)
console.log(this)
},
//destroyed: 组件完成销毁
destroyed(){
console.log(8)
console.log(this)
}
}
</script>
<style>
</style>