时间:2022-11-28 10:28:26 | 栏目:vue | 点击:次
生命周期:又名:生命周期回调函数、生命周期函数、生命周期钩子
生命周期是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数 3.生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的 4.生命周期函数中的 this 指向是 vm 或组件实例对象
做一个小例子,要求页面的文字一上来透明度就周而复始的从1变到0
<div id="root">
<h2 :style="{opacity: opacity}">好好学习</h2>
<h2 :style="{opacity}">天天向上</h2>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
//创建vue实例
new Vue({
el: "#root",
data: {
opacity: 1
},//Vue完成模板解析,并把初始的真实dom放入页面后(挂载完毕)调用mounted
mounted(){
setInterval(()=>{
this.opacity -= 0.01
if(this.opacity <=0) this.opacity = 1
},20)
}
})
</script>



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue初识</title>
<script type="text/javascript" src="./js/vue.js"></script>
</head>
<body>
<div id="root">
<h2 :style="{opacity}">天天向上</h2>
<button @click="opacity = 1">透明度设置为1</button>
<button @click="stop">点我停止变换</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
//创建vue实例
new Vue({
el: "#root",
data: {
opacity: 1
},
methods:{
stop(){
this.$destroy()
}
},
mounted(){
this.timer = setInterval(()=>{
this.opacity -= 0.01
if(this.opacity <=0) this.opacity = 1
},20)
},
beforeDestroy(){
console.log("beforeDestroy")
clearInterval(this.timer)
}
})
</script>
</body>
</html>

vm的一生(vm的生命周期):
beforeCreate函数created豳数beforeMount函数mounted函数【重要的钩子】beforeUpdate函数updated函数。beforeDestroy函数【重要的钩子】destroyed函数常用的生命周期钩子:
mounted:发送ajax请求、启动定时器、绑定自定义事件、订阅消息等【初始化操作】beforeDestroy:清除定时器、解绑自定义事件、取消订阅消息等【收尾工作】关于销毁Vue实例:
beforeDestroy操作数据,因为即便操作数据,也不会再触发更新流程了