可以关注一下我的公众号!!! 精彩文章等着您。

1.什么是生命周期
首先,我们了解一下"生命周期"这个词。 通俗的来说,生命周期就是一个事务从出生到消失的过程。例如,一个人从出生到去世。 在vue中,vue的生命周期是指,从创建vue对象到销毁vue对象的过程。
Vue实例有一个完整的生命周期,也就是从开始创建、初始化数据、编译模板、挂载Dom、渲染→更新→渲染、卸载等一系列过程,我们称这是Vue的生命周期。通俗说就是Vue实例从创建到销毁的过程,就是生命周期。
在Vue的整个生命周期中,它提供了一系列的事件,可以让我们在事件触发时注册js方法,可以让我们用自己注册的js方法控制整个大局,在这些事件响应方法中的this直接指向的是vue的实例。
2.钩子函数
【解释】:
钩子函数是Vue框架中内置的一些函数,随着Vue的生命周期阶段,自动执行
钩子函数是Vue框架中内置的一些函数,随着Vue的生命周期阶段,自动执行
【作用】:
特定的时间,执行特定的操作
特定的时间,执行特定的操作
【分类】:
四大阶段,八大方法
| 阶段 | 方法名 | 方法名 |
|---|---|---|
| 初始化 | beforeCreate | created |
| 挂载 | beforeMount | mounted |
| 更新 | beforeUpdate | updated |
| 销毁 | beforeDestroy | destroyed |
3、Vue生命周期之初始化阶段
【图示】:
【代码演示1】:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<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>Title</title>
<script src="js/vue.min.js"></script>
</head>
<body>
<div id="root">
<h2 :style="{opacity}">欢迎学习</h2>
{{ change() }}
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip=false;
new Vue({
el:'#root',
data:{
opacity:1
},
methods:{
change(){
console.log('开启了一个定时器')
setInterval(()=>{
this.opacity-=0.01
if(this.opacity<=0)
{
this.opacity=1
}
},16)
}
}
})
</script>
</html>
【代码分析】:
【代码演示2】:
<template>
<div>
<h3>生命周期函数</h3>
<button @click="message='测试'">修改数据</button>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
name: "life",
data(){
return {
message:"hello"
}
},
beforeCreate()
{
console.log("beforeCreate -->创建前");
console.log(this.message);
},
created(){
console.log("created -->创建后");
console.log(this.message);
},
beforeMount(){
console.log("beforeMount --> 渲染前");
console.log(this.message);
},
mounted(){
console.log("mounted --> 渲染后");
console.log(this.message);
},
beforeUpdate(){
console.log("beforeUpdate --> 修改前");
console.log(this.message);
},
updated(){
console.log("updated --> 修改后");
console.log(this.message);
},
beforeDestroy(){
console.log("beforeDestroy --> 销毁前");
console.log(this.message);
},
destroyed(){
console.log("destroyed --> 销毁后");
console.log(this.message);
}
}
</script>
<style scoped>
</style>