6

【vue】Vue实例的生命周期

 2 years ago
source link: https://segmentfault.com/a/1190000040717177
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Vue实例的生命周期

官网生命周期图示

  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
  5. beforeUpdate
  6. updated
  7. beforDestroy
  8. destroyed

其他lifecycle_hook

keep-alive配合使用的activateddeactivated
捕获错误errorCaptured
处理ssrserverPrefetch

各阶段生命周期函数说明

1 beforeCreate created

这两个hook是在模板编译之前,初始化阶段执行
源码

在调用beforeCreate之前

  • 初始化生命周期
  • 初始化事件
  • 初始化render

在调用created之前

  • 初始化注入
  • 初始化状态
  • 初始化provide

initState

  function initState (vm) {
    vm._watchers = [];
    var opts = vm.$options;
    if (opts.props) { initProps(vm, opts.props); }
    if (opts.methods) { initMethods(vm, opts.methods); }
    if (opts.data) {
      initData(vm);
    } else {
      observe(vm._data = {}, true /* asRootData */);
    }
    if (opts.computed) { initComputed(vm, opts.computed); }
    if (opts.watch && opts.watch !== nativeWatch) {
      initWatch(vm, opts.watch);
    }
  }

初始化状态

  • initProps
  • initMethods
  • initData
  • initComputed
  • initWatch

initState的调用在beforeCreatecreated之间,所以
beforeCreate获取不到vm上的data与methods
created能获取到

2 beforeMount mounted

beforeMount在模板编译后,挂载前,mounted在挂载之后

调用beforeMount之前

调用mounted之前

  • 将编译好的模板挂载到页面

源码
image.png

beforeMount上能获取模板信息,但是页面未显示
mounted页面挂载完成

mounted为止,从无到有,创建阶段完成
在运行阶段未发生销毁,不会再调用以上hooks

3 beforeUpdate updated

运行阶段的hooks
beforeUpdate在数据改变后页面渲染前,updated在新数据渲染到页面后
在上面的源码中可以看到,watcher侦测到数据变化时就会调用beforeUpdate
image.png
在数据更新完成后会调用updated

4 beforeDestroy destroyed

在调用$destroy时会调用这两个hook
image.png
beforeDestoy之后开始销毁

  • 从父级拆除

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK