web前端-初探Vue生命周期

网友投稿 688 2022-05-30

一、vue的生命周期是什么

vue每个组件都是独立的,每个组件都有一个属于它的生命周期,从一个组件创建、数据初始化、挂载、更新、销毁,这就是一个组件所谓的生命周期。

,首先看一张图吧,这是官方文档上的图片,图中可以看到在组件中具体的方法有:

vm创建:new Vue()

初始化显示:beforeCreate()----created()---beforeMount()---mounted() 到此初始化结束

更新显示:beforeUpdate()---updated() 数据更新

销毁vm实例:vm.$destroy()---beforeDestroy()---destroyed() vm死亡

上一波代码,console查看:

         10     

{{message}}

    destroy vm     生命周期

{//用箭头函数可以保证this是外部的对象                 console.log("-----")                 this.isShow=!this.isShow             },1000)         },         //更新阶段         beforeUpdate(){             console.log('beforeUpdate()')             console.log("el    :"+this.$el)             console.log("data    :"+this.$data)             console.log("message    :"+this.message)         },         updated(){             console.log('updated()')             console.log("el    :"+this.$el)             console.log("data    :"+this.$data)             console.log("message    :"+this.message)         },         //死亡阶段         beforeDestroy(){//死亡之前调用(一次)             console.log('beforeDestroy()')             console.log("el    :"+this.$el)             console.log("data    :"+this.$data)             console.log("message    :"+this.message)             clearInterval(this.intervalId)//清除定时器         },         destroyed(){             console.log('destroyed()')             console.log("el    :"+this.$el)             console.log("data    :"+this.$data)             console.log("message    :"+this.message)         },         methods:{             destroyVm(){                 this.$destroy()//销毁vm             }         }     })

web前端-初探Vue生命周期

下面分析各个阶段调用生命周期的函数:

1.beforeCreate()进行初始化事件,进行数据观测,可以看到在created()的时候数据已经和data属性进行绑定,注意此时还没有el选项

2.到beforeMount()阶段,el选项已被挂载

3.由于设置了定时器,每一秒后data中的isShow变量会改变,即先后调用了beforeUpdate()和updated()函数

4.beforeDestroy():收尾工作,如清除定时器,在这一步,实例任然完全可用

5.destroyed():调用后,Vue实例指示的所有东西会解绑定,所有事件监听器会被移除,页面上的所有组件都不再变化了。

总结:vue 的生命周期,总得来说就是实例的创建和销毁这段时间的一个机制,也是vue框架的数据间的交互通信,弄清楚了它的各个阶段对以后的开发大有帮助

最后,天道酬勤,加油!

web前端 Vue

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:用快递鸟物流API接口查询各快递物流信息(java)
下一篇:浏览器自动化框架比较:Selenium,Puppeteer和Cypress.io
相关文章