总结vue生命周期所学
前言
之前写的博客多是以总结知识点为主,但写完我发现过了很久即使我忘记了那些知识点也还是会去百度,不会重看我的博客,所以从这篇开始想多以在学习时遇到的问题以及思考为主,记录在遇到问题时的解决思路和方法,以此加深印象。
Vue生命周期
先放一张vue官方文档图
首先,在生命周期钩子函数中,this都指向调用它的Vue实例,并且在写生命周期函数时不要使用箭头函数的写法。这是两个需要注意的点。
其次用我自己的理解解释一下各个生命周期函数主要在做什么:
- beforeCreate()函数:在初始化实例之后,此时Vue实例的options对象还未创建,el和data等options还没有初始化,因此还无法访问data、methods、computed等数据和方法。
- created()函数:实例创建完成后调用,但还没有完成el的初始化,完成了data数据的初始化,可以访问methods、computed等属性和方法。通常我们可以在这一步对实例进行预处理、做网络请求(ajax)等相关操作。
- beforeMount()函数:Vue实例已经完成模板的编译,完成了el和data的初始化,但还没有挂载到html页面上。
- Mounted()函数:挂载完成,模板中的HTML会渲染到HTML页面上。此时可以做一些ajax操作,该函数只会执行一次。
- beforeUpdate()函数:当数据发生更新时被调用。
- updated()函数:虚拟DOM渲染补丁。
- beforeDestroy()函数:实例销毁之前调用。这里使用this还可以获取实例。这里一般做重置操作,例如:清楚组件中的定时器、清除监听事件等
- destroyed()函数:实例销毁之后调用,所有事件监听器被移除,子实例也会被销毁。
最后,写一个代码来实践~
<!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>vue生命周期</title>
<script src="../../js/vue.js"></script>
</head>
<body>
<div id="app">
<input type="button" value="A组件" @click="currentTabComponent='a_component'" />
<input type="button" value="B组件" @click="currentTabComponent='b_component'" />
<component :is="currentTabComponent"></component>
</div>
<script>
const v = new Vue({
el: '#app',
data() {
return {
number: 10,
currentTabComponent: 'a_component',
};
},
methods: {
},
components: {
a_component: {
template: '<h1>我是A组件</h1>',
beforeCreate() {
console.log('a_component beforeCreate')
},
created() {
console.log('a_component created')
},
beforeMount() {
console.log('a_component beforeMount')
},
mounted() {
console.log('a_component mounted')
},
beforeDestroy() {
console.log('a_component beforeDestroy')
},
destroyed() {
console.log('a_component destroyed')
}
},
b_component: {
beforeCreate() {
console.log('b_component beforeCreate')
},
created() {
console.log('b_component created')
},
beforeMount() {
console.log('b_component beforeMount')
},
mounted() {
console.log('b_component mounted')
},
template: '<h1>我是B组件</h1>',
beforeDestroy() {
console.log('b_component beforeDestroy')
},
destroyed() {
console.log('b_component destroyed')
}
}
}
});
</script>
</body>
</html>
Vue实例初始化时调用A组件,并调用了四个生命周期函数,等待beforeUpdate和beforeDestroy的调用。
然后点击B组件按钮,调用组件B的四个生命周期函数,并对A逐渐执行beforeDestroy()与destoryed()函数。