vue生命周期详述,这次来聊一下vue的生命周期!
可以看到vue一整个的生命周期中会有很多钩子函数提供给我们在vue生命周期不同的时刻进行操作,那么先列出所有的钩子函数,然后慢慢来!
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeDestroy
destroyed
什么是vue的生命周期?
这么说吧:vue实例从创建到销毁的过程,就是生命周期。也就是从 开始创建、初始化数据、编译模板、挂载DOM-渲染、更新-渲染、卸载,等等一系列的过程,我们称之为vue的生命周期
vue生命周期的作用是什么呢?
vue所有的功能的实现都是围绕其生命周期进行的,在生命周期的不同阶段调用对应的钩子函数可以实现组件数据管理和DOM渲染两大重要功能。生命周期中有多个事件钩子,在控制整个vue实例的过程时更容易形成好的逻辑!
那么,真正的问题来了,第一次页面加载会触发哪几个钩子呢?
那么我们来实现一下,实际测试一波
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>生命周期</title> <script src="../../vue.js"></script> </head> <body> <div id="app"> <h1>{{message}}</h1> </div> </body> <script type="text/javascript"> let vm = new Vue({ el:'#app', data:{ message:'angula' }, beforeCreate:function(){ console.group('------beforeCreate创建前状态------'); console.log("%c%s",'color:red','el :'+this.$el); console.log("%c%s",'color:red','data :'+this.$data); console.log("%c%s",'color:red','message :'+this.message); }, created:function(){ console.group('------create创建后状态------'); console.log("%c%s",'color:red','el :'+this.$el); console.log("%c%s",'color:red','data :'+this.$data); console.log("%c%s",'color:red','message :'+this.message); }, beforeMount:function(){ console.group('------beforeMount挂载前状态------'); console.log("%c%s",'color:red','el :'+this.$el); console.log(this.$el); console.log("%c%s",'color:red','data :'+this.$data); console.log("%c%s",'color:red','message :'+this.message); }, mounted:function(){ console.group('------mounted挂载后状态------'); console.log("%c%s",'color:red','el :'+this.$el); console.log(this.$el); console.log("%c%s",'color:red','data :'+this.$data); console.log("%c%s",'color:red','message :'+this.message); }, beforeUpdate:function(){ console.group('------beforeUpdate更新前状态------'); console.log("%c%s",'color:red','el :'+this.$el); console.log("%c%s",'color:red','data :'+this.$data); console.log("%c%s",'color:red','message :'+this.message); }, updated:function(){ console.group('------updated更新完成状态------'); console.log("%c%s",'color:red','el :'+this.$el); console.log("%c%s",'color:red','data :'+this.$data); console.log("%c%s",'color:red','message :'+this.message); }, beforeDestroy:function(){ console.group('------beforeDestroy销毁前状态------'); console.log("%c%s",'color:red','el :'+this.$el); console.log("%c%s",'color:red','data :'+this.$data); console.log("%c%s",'color:red','message :'+this.message); }, destroyed:function(){ console.group('------destroyed 销毁后状态------'); console.log("%c%s",'color:red','el :'+this.$el); console.log("%c%s",'color:red','data :'+this.$data); console.log("%c%s",'color:red','message :'+this.message); }, }) </script> </html>
从上面可以看到,第一次页面加载hi触发4个钩子函数哦!
beforeCreate , created , beforeMount ,mounted 这几个钩子
1. 在beforeCreate和created钩子函数之间的生命周期
在这个生命周期之间,进行初始化事件,进行数据的观测,可以看到,在created的时候,数据已经和data属性进行绑定(放在data中的属性当值发生改变的同时,视图也会发生改变),注意:此时并没有el选项哦!
本文地址:百科问答频道 https://www.neebe.cn/wenda/903243.html,易企推百科一个免费的知识分享平台,本站部分文章来网络分享,本着互联网分享的精神,如有涉及到您的权益,请联系我们删除,谢谢!