100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > vue父子组件生命周期执行顺序_关于Vue组件的生命周期及执行顺序

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

时间:2020-03-12 04:02:07

相关推荐

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 (){

})

}

参考资料

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。