Vue生命周期是什么?
在vue的创建、使用、销毁的过程中,有许多事件,这些事件统称为生命周期函数。
换而言之,生命周期就是Vue在关键时刻帮我们调用的一些特殊名称的函数。
Vue生命周期主要分为四个阶段,八个过程
四个阶段:
- Create 创建
- Mount 挂载
- Update 更新
- Destroy 销毁
八个过程:
- beforeCreate 创建完成之前
- created 创建完成之后
- beforeMount 挂载完成之前
- mounted 挂载完成之后
- beforeUpdate 数据更新之前
- updated 数据更新之后
- beforeDestroy vue实例销毁之前
- destroyed vue实例销毁之后
生命周期图示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue的生命周期</title>
</head>
<body>
<!-- 容器/模板 -->
<div id="app">
<h2>This is {{times}}</h2>
<button @click="add">点击+1</button>
<button @click="des">毁灭吧,赶紧的</button>
</div>
</body>
<!-- 引入Vue.js -->
<script src="../js/vue.min.js"></script>
<script>
new Vue({
el:'#app',
data:{
times:0
},
methods:{
add(){
this.times++;
},
des(){
this.$destroy();
}
},
// Vue生命周期钩子函数
// 创建完成之前,无法通过vm访问到data中的数据,methods中的方法
beforeCreate() {
console.log('I am beforeCreate');
//console.log(this.times); //undefined
//this.add(); //this.add is not a function
},
// 创建完成之后,可以通过vm访问data中的数据和methods中的方法
created() {
console.log('I am created');
//console.log(this.times); //0
//this.add(); //this.time++
},
// 挂载完成之前,vue会将el对应的模板挂载到vm.$el中去,但还没有挂载上去,在页面中还没有显示
beforeMount() {
console.log('I am beforeMont');
//页面显示的是This is {{times}}
},
// 挂载完成之后,vue将真实DOM挂载到页面中
mounted() {
console.log('I am mounted');
// 页面显示的是This is 0
},
// 数据更新完成之前,页面渲染的数据和data中的数据不一致,只有data的数据发生改变时才会调用这个钩子函数
beforeUpdate() {
console.log('I am beforeUpdate');
//console.log(this.times);//1
// 当点击一次自增按钮时,页面渲染的数据为This is 0,而data中的数据已经变为1,明显不一致
},
// 数据更新完成,更新完再渲染,谁改变渲染谁,而不是整个DOM树
updated() {
console.log('I am updated');
//console.log(this.times);
// 页面渲染的数据和data中的数据一致
},
// 实例销毁完成前,销毁操作需要手动调用,调用Vue实例中的.$destroy()方法,上面通过按钮实现
beforeDestroy() {
console.log('I am beforeDestroy')
// 实例销毁完成前,仍然可以访问到data中的数据
// console.log(this.times); //0
},
// 实例销毁完成之后
destroyed() {
console.log('I am destroyed');
// 实例销毁完成之后,组件中的数据、方法指令...等都不可用了
//console.log(this.times);
},
})
</script>
</html>