ITPub博客

首页 > IT职业 > IT职场 > Vuejs 生命周期

Vuejs 生命周期

IT职场 作者:nanquanc 时间:2021-09-09 09:59:31 0 删除 编辑

每个 Vue 实例在被创建时都要经过一系列的初始化过程。如需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会。

一个 Vue 实例

我们创建一个 Vue 实例,并在每个阶段验证 Vue 的生命周期函数。

Vue 实例的生命周期函数并不放置在 methods里,而是单独放置在 Vue 的实例之中。

html>
  
  Vue实例生命周期函数
  
  
  
",      data: {        test: "hello world"       },      // Vue初始化       beforeCreate: function(){        console.log('beforeCreate')       },      created: function(){        console.log('created')       },      //页面渲染之前 挂载之前的时间点       beforeMount: function(){        console.log('beforeMount')        console.log(this.$el)       },      // 挂载到页面之后       mounted: function(){        console.log('mounted')        console.log(this.$el)       },      //当数据发生改变的时候 执行       beforeUpdate: function(){        console.log('beforeUpdate')       },      updated: function(){        console.log('updated')       },      // vm.$destroy()被called的时候触发       beforeDestroy: function(){        console.log('beforeDestroy')       },      destroyed: function(){        console.log('destroyed')       }     })  


生命周期函数

生命周期函数就是Vue实例在某一个时间点会自动执行的函数

  • Vue 初始化:beforeCreate 、created

  • 页面渲染之前:beforeMount

  • 挂载到页面之后:mounted

图片描述

  • 当数据发生改变时:beforeDestroy(重新渲染之前) 、destroyed(重新渲染之后)

图片描述

  • vm.$destroy()被调用时,即组件被销毁时:beforeDestroy 、destroyed

图片描述


生命周期图

下图展示了 Vue 实例的声明周期,结合上一节的示例,可以更好的理解 Vue 的这八个声明周期钩子。


图片描述




其他

除此之外 Vue 还拥有 activated、deactivated 、errorCaptured 这三个生命周期钩子。

activated

当页面重新显示的时候,执行。搭配 keep-alive、localStrage 和临时变量做页面性能优化。

deactivated

当页面即将被隐藏或替换成其他页面时,执行。可以用来解绑在 activated 上绑定的全局事件。



作者:evenyao
链接:https://www.jianshu.com/p/c8a7306aa844


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1556/viewspace-2814709/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    109
  • 访问量
    854