一、Vue生命周期函数是什么?
Vue生命周期函数又称生命周期钩子
主要分为三个阶段
第一是初始化显示阶段
主要函数有以下几个
beforeCreate():
此时,无法通过vm访问到data中的数据、methods中的方法
created():
此时,可以通过vm访问到data中的数据、methods中的方法
beforeMount():
此时,1、页面呈现的是未经Vue编译的DOM结构
2、所有对DOM的操作,最终都不生效
mounted()
此时,1、页面呈现的是经过Vue编译的DOM结构
2、对DOM的操作均有效(尽可能避免)
至此初始化过程结束,一般在此进行:开启定时器、发送网络请求、订阅消息、绑定自定义事件等初始化操作
第二个阶段是更新状态
beforeUpdate()
updated()
第三十 销毁 vue 实例: vm.$destory()
* beforeDestory()
* destoryed()
代码如图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../../js/vue.js"></script>
</head>
<body>
<div id="root">
<h2>当前的值是{{n}}</h2>
<button @click="n++">点击让n+1</button>
<button @click="bye">点我销毁vm</button>
</div>
<script>
new Vue({
el:'#root',
data:{
n:1
},
methods: {
add(){
this.n++
},
bye(){
console.log('bye');
this.$destroy()
}
},
beforeCreate() {
console.log('beforeCreate')
console.log(this)
},
created() {
console.log('created')
},
// 这里生命周期函数beforeMount():
// 1、页面呈现的是未经Vue编译的DOM结构
// 2、所有对DOM的操作,最终都不生效
beforeMount() {
console.log('beforeMount')
},
Mounted(){
console.log('Mounted');
},
beforeUpdate() {
console.log('beforeUpdate');
},
updated() {
console.log('update')
},
destroyed() {
console.log('destroyed')
},
})
</script>
</body>
</html>
控制台输出如图
常用的生命周期方法
1. mounted(): 发送 ajax 请求, 启动定时器等异步任务
2. beforeDestory(): 做收尾工作, 如: 清除定时器
整个流程环节图为
1.14.4. 常用的生命周期方法
1. mounted(): 发送 ajax 请求, 启动定时器等异步任务
2. beforeDestory(): 做收尾工作, 如: 清除定时器