关于Vue组件的生命周期及执行顺序


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/01/12/%E5%85%B3%E4%BA%8EVue%E7%BB%84%E4%BB%B6%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%8F%8A%E6%89%A7%E8%A1%8C%E9%A1%BA%E5%BA%8F/

摘要

本文主要讲述了:

  1. 组件渲染时的生命周期
  2. 组件数据变更时的生命周期
  3. 组件嵌套时的生命周期

正文

组件渲染时的生命周期

在组件渲染时,每个 Vue 组件都有 4 个生命周期,分别是:

  • beforeCreate()
  • created()
  • beforeMount()
  • mounted()

All lifecycle hooks automatically have their this context bound to the instance, so that you can access data, computed properties, and methods. This means you should not use an arrow function to define a lifecycle method (e.g. created: () => this.fetchTodos()). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.

所有的生命周期都会自动把this指向组件实例本身,因此你可以使用this来访问数据、计算属性和方法。这意味着你不应该使用箭头函数来定义生命周期(例如: created: () => this.fetchTodos())。因为箭头函数的this指向父上下文,不会是你期望的组件实例。

注意:在beforeCreate()阶段,属性和方法还没有挂载,因此无法通过this去访问它们。

在组件渲染的过程中,生命周期的执行顺序是:

Lifecycle Order
beforeCreate() 1
created() 2
beforeMount() 3
mounted() 4

组件数据变更时的生命周期

在组件数据变更时,每个 Vue 组件都有 2 个生命周期,分别是:

  • beforeUpdate()
  • updated()

在组件数据变更时,生命周期的执行顺序是:

Lifecycle Order
beforeUpdate() 1
updated() 2

组件嵌套时的生命周期

我们假定 2 个组件,Father.vueChild.vue,它们是父子组件关系。

组件渲染时的生命周期执行顺序

在组件渲染时,生命周期的执行顺序是:

Component Lifecycle Order
father.vue beforeCreate() 1
father.vue created() 2
father.vue beforeMount() 3
child.vue beforeCreate() 4
child.vue created() 5
child.vue beforeMount() 6
child.vue mounted() 7
father.vue mounted() 8

Note that mounted does not guarantee that all child components have also been mounted. If you want to wait until the entire view has been rendered, you can use vm.$nextTick inside of mounted

注意父组件的mounted()不保证在所有子组件都执行完mounted()之后才执行。如果你想要这么做,你可以用vm.$nextTick来代替mounted()

1
2
3
4
5
mounted: function () {
this.$nextTick(function () {
// 这里的代码会在所有子组件都执行完mounted()之后才会执行
})
}

组件数据变更时的生命周期执行顺序

在组件数据变更时,生命周期的执行顺序是:

Component Lifecycle Order
father.vue beforeUpdate() 1
child.vue beforeUpdate() 2
child.vue updated() 3
father.vue updated() 4

Note that updated does not guarantee that all child components have also been re-rendered. If you want to wait until the entire view has been re-rendered, you can use vm.$nextTick inside of updated.

注意父组件的updated()不保证在所有子组件都执行完updated()之后才执行。如果你想要这么做,你可以用vm.$nextTick来代替updated()

1
2
3
4
5
updated: function () {
this.$nextTick(function () {
// 这里的代码会在所有子组件都执行完`updated()`之后才会执行
})
}

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/01/12/%E5%85%B3%E4%BA%8EVue%E7%BB%84%E4%BB%B6%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%8F%8A%E6%89%A7%E8%A1%8C%E9%A1%BA%E5%BA%8F/


本文对你有帮助?请支持我


支付宝
微信