vue父子组件生命周期执行顺序_关于Vue组件的生命周期及执行顺序

本文主要讲述了:Vue组件渲染时的生命周期及执行顺序

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

Vue组件嵌套时的生命周期及执行顺序

正文

组件渲染时的生命周期

在组件渲染时,每个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去访问它们。

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

created()2

beforeMount()3

mounted()4

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

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

updated()

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

updated()2

组件嵌套时的生命周期

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

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

在组件渲染时,生命周期的执行顺序是:ComponentLifecycleOrderfather.vuebeforeCreate()1

father.vuecreated()2

father.vuebeforeMount()3

child.vuebeforeCreate()4

child.vuecreated()5

child.vuebeforeMount()6

child.vuemounted()7

father.vuemounted()8Note 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

5mounted: function (){

this.$nextTick(function (){

})

}

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

在组件数据变更时,生命周期的执行顺序是:ComponentLifecycleOrderfather.vuebeforeUpdate()1

child.vuebeforeUpdate()2

child.vueupdated()3

father.vueupdated()4

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

2

3

4

5updated: function (){

this.$nextTick(function (){

})

}

参考资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值