本文从vue生命周期的基础与应用两块进行介绍
一.基础
打开vue文档,我们可以看到vue的生命周期图
然后我们通过一个简单的demo来理解一下,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue实例生命周期函数</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app"></div>
<div id="app2"></div>
<script>
// 生命周期函数就是vue实例在某一个时间点自动执行的函数
var vm = new Vue({
el: '#app',
template: '<div>{{test}}</div>', // 此模板会替换掉id为app的div
data: {
test: "hello world"
},
beforeCreate: function () {
console.log("beforeCreate")
console.log(this.$el)
},
created: function () {
console.log("created")
console.log(this.$el)
},
// 此时数据还未渲染到页面
beforeMount: function () {
console.log("beforeMount")
console.log(this.$el)
},
// 首次创建el或者el发生改变时执行(控制台执行vm.$mount('#app2'))
// 此时数据已渲染到页面
mounted: function () {
console.log("mounted")
console.log(this.$el)
},
// 控制台执行 vm.$destroy() 语句才执行以下方法
// 组件开始被销毁时执行
beforeDestroy: function () {
console.log("beforeDestroy")
},
// 组件被完全销毁时执行
destroyed: function () {
console.log("destroyed")
},
// 数据改变时执行 控制台输入vm.test = 'bye'
// 数据开始改变,还未渲染到页面时执行
beforeUpdate: function () {
console.log("beforeUpdate")
console.log(this.$el)
},
// 数据已改变,渲染到页面时执行
updated: function () {
console.log("updated")
console.log(this.$el)
}
})
</script>
</body>
</html>
打开浏览器控制台看运行结果:
我们可以看见,在页面初始化时只执行了四个生命周期函数,即:
beforeCreate, created, beforeMount, mounted 经历了创建与挂载的过程
当我们执行vm.$mount('#app2')命令修改el挂载点时,又先后执行了
beforeMount,beforeUpdate,mounted
如下:
然后我们执行vm.test = 'bye'修改data中的数据时,则会先后执行
beforeUpdate,updated方法,如下:
最后,我们执行vm.$destroy()销毁vue实例时,则会执行
beforeDestroy,destroyed方法,如下:
通过以上 demo和生命周期图相信对整个vue的生命周期函数执行的流程有一个大致的了解了。
当然,vue的声明周期不止这8个,还有activated,deactivated,errorCaptured。前两个是使用 keep-alive 组件 时才会用到,这里不介绍。
二.应用
1.数据初始化
我们一般在created生命周期中进行组件的初始化工作,比如数据的初始化
created() {
this._init()
},
但是,如果我们要操作 DOM,这时 created 中 this.$refs 为空,所以我们需要在 mounted 生命周期中进行初始化工作
mounted() {
this._init()
},
2.全局事件的绑定与解绑
mounted () {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy () {
window.removeEventListener('scroll', this.handleScroll)
}
当全局事件只需在当前页面绑定的时候,为了优化性能,我们需要在离开当前页面时解绑。这里,我们还可以用下面的写法,将事件绑定与解绑放在一起
mounted () {
window.addEventListener('scroll', this.handleScroll)
// 通过hook监听组件销毁钩子函数,并取消监听事件。这里也可用 $on
this.$once('hook:beforeDestroy', () => {
window.removeEventListener('scroll', this.handleScroll)
})
},
3.其他
当我们拿捏不准当前页面或组件会执行哪写生命周期函数时,不妨将这些生命周期函数打印出来,然后合理的在其中添加我们的业务逻辑。