您好,欢迎访问一九零五行业门户网

Vue实例的生命周期详解之从创建到销毁全过程

本篇文章给大家带来了关于vue的相关知识,其中主要介绍了关于vue实例的生命周期从创建到销毁的全过程,生命周期是每个vue实例在被创建时都要经过一系列的初始化过程,下面一起来看一下,希望对大家有帮助。
【相关推荐:javascript视频教程、vue.js教程】
vue的生命周期一直以来都是重中之重,虽然在实际开发中经常用到的就几个,但是你对生命周期的掌握程度决定着你写的程序好不好,并且这一块也一直是面试vue部分的重要考点。
初识new vue关于new vue 大家应该都知道,new关键字在js中是实例化一个对象。那么 new vue 都干了啥?
其实,new vue就是创建了一个vue实例,vue实例上是一个类,new vue实际上是执行了vue类的构造函数
创建vue实例:
let vm = new vue({   el: #app,   data: {       name: 'beiyu'   },}
那么关于这个实例,从它初始化到销毁,都经历了什么呢?下面一起来看看:
vue实例从创建到销毁实例从创建到销毁的过程我们称作生命周期
生命周期的基本概念:
每个vue实例在被创建时都要经过一系列的初始化过程。
例如:需要设置数据监听、编译模板、将实例挂载到dom并在数据变化时更新dom等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了使用者在不同阶段添加自己代码的机会。
1.创建之前—beforecreate()vue实例对象创建之前
el属性和data属性均为空,常用于初始化非响应式变量
beforecreate() {    console.group(---创建前beforecreate---)    console.log('%c%s', 'color: red', 'el:' + this.$el)    console.log('%c%s', 'color: red', 'data:' + this.$data)},
2.创建之后—created()vue实例对象创建之后
data属性存在,el属性为空,ref属性内容为空数组,常用于进行axios请求,页面的初始化等。但是这里不要请求过多,否则会出现长时间的白屏现象。
created() {    console.group(---创建之后created---)    console.log('%c%s', 'color: red', 'el:' + this.$el)    console.log('%c%s', 'color: red', 'data:' + this.$data, this.$data.name)},
3.实例对象和文档挂载之前—beforemount()vue实例对象和文档挂载之前,会去找对应的template
beforemount() {    // 这个时候$el属性是绑定之前的值    console.group(---挂载之前beforemount---)    console.log('%c%s', 'color: red', 'el:' + this.$el, this.$el.innerhtml)    console.log('%c%s', 'color: red', 'data:' + this.$data, this.$data.name)},
4.实例对象和文档挂载之后—mounted()vue实例对象和文档节点挂载之后
el属性存在,ref属性可以访问
mounted() {    console.group(---挂载之后mounted---)    console.log('%c%s', 'color: red', 'el:' + this.$el, this.$el.innerhtml)    console.log('%c%s', 'color: red', 'data:' + this.$data, this.$data.name)},
5.视图更新前—beforeupdate()view视图更新之前
响应式数据更新时调用
beforeupdate() {    console.group(---更新之前beforeupdate---)    console.log('%c%s', 'color: red', 'el:' + this.$el, this.$el.innerhtml)},
6.视图更新后—updated()view视图更新之后
dom更新完毕,不要在这里操作数据,可能陷入死循环
updated() {    console.group(---更新之后updated---)    console.log('%c%s', 'color: red', 'el:' + this.$el, this.$el.innerhtml)},
7.实例销毁之前—beforedestroy()vue实例对象销毁之前|此时el和data全都还在,一般会在这一步进行销毁定时器、解绑全局事件、销毁插件对象等操作。
beforedestroy() {    console.group(---销毁之前beforedestroy---)    console.log('%c%s', 'color: red', 'el:' + this.$el, this.$el.innerhtml)},
8.实例销毁之后—destroyed()vue实例对象销毁之后|
destroyed() {    console.group(---销毁之后destroyed---)    console.log('%c%s', 'color: red', 'el:' + this.$el, this.$el.innerhtml)},
总结vue2生命周期就是以上8个过程,在页面中我们来看一看,上面的打印结果:
从页面打开到完成一共经过四个生命周期,因为这里页面没有其他操作,所以剩下的四个生命周期没有对应的显示出来
【相关推荐:javascript视频教程、vue.js教程】
以上就是vue实例的生命周期详解之从创建到销毁全过程的详细内容。
其它类似信息

推荐信息