你真的了解Vue的生命周期吗?

前端开发
2020年06月03日
786

相信熟悉Vue的朋友对于Vue的生命周期钩子都不陌生吧,那么对于beforeCreate中访问data数据以及嵌套组件中的生命周期钩子触发的顺序这两个问题是否也有研究呢?

beforeCreate钩子里面可以访问到data中的数据吗?

js
export default { name: 'Test', data () { return { number: 123456 } }, props: { info: { type: String, default () { return 'test' } } }, beforeCreate () { // console.log(this.info); // [Vue warn]: Error in beforeCreate hook: "TypeError: Cannot read property 'info' of undefined" console.log('beforeCreate: ', this.number) }, created () { console.log('created: ', this.info, this.number); } }
plain-text
logs: beforeCreate: undefined created: 'test' 123456

很显然,在beforeCreate生命周期钩子里面,我们无法获取到data中的数据。

从生命周期的图示,我们可以看出,数据的注入以及校验都是在beforeCreate钩子触发之后才会进行,所以我们无法在beforeCreate钩子里面获取到data中的数据。

1.png

那么,methods里面的方法是否可以访问呢?

js
export default { name: 'Test', methods: { test () { console.log('test'); } }, beforeCreate () { console.log('---------- beforeCreate ----------'); console.log(this.test); this.test(); }, created () { console.log('---------- created ----------'); console.log(this.test); this.test(); }, }
plain-text
logs: ---------- beforeCreate ---------- undefined [Vue warn]: Error in beforeCreate hook: "TypeError: this.test is not a function" ---------- created ---------- ƒ test() { console.log('test'); } test

显然,methods里面的方法也无法在beforeCreate里面访问到。

注意:beforeCreate里面的this指向和其它生命周期钩子的指向是致的,都是指向该组件实例本身。这一点在Vue的官方文档中也是有提及的。

嵌套组件中的生命周期钩子的触发顺序

嵌套结构:

QQ截图20200603003343.jpg

输出结果:

beforeCreatecreatedbeforeMountmounted

plain-text
page - beforeCreate page - created page - beforeMount wrapper - beforeCreate wrapper - created wrapper - beforeMount header - beforeCreate header - created header - beforeMount title - beforeCreate title - created title - beforeMount list - beforeCreate list - created list - beforeMount item - beforeCreate item-001 - created item-001 - beforeMount item - beforeCreate item-002 - created item-002 - beforeMount title - mounted header - mounted item-001 - mounted item-002 - mounted list - mounted wrapper - mounted page - mounted

可以看出,从beforeCreatebeforeMount是先从外层触发然后一层一层的往里层触发,而mounted钩子则是里层先触发,然后再一层层往外层触发。

beforeDestroydestroyed

plain-text
page - beforeDestroy wrapper - beforeDestroy header - beforeDestroy title - beforeDestroy title - destroyed header - destroyed list - beforeDestroy item-001 - beforeDestroy item-001 - destroyed item-002 - beforeDestroy item-002 - destroyed list - destroyed wrapper - destroyed page - destroyed

beforeDestroy也是从外层向里层触发,而destroyed则与mounted的触发顺序一致,也是从里层向外层触发,直接最外层卸载完毕,从而完成整个组件的卸载过程。

beforeUpdateupdated

plain-text
page - beforeUpdate wrapper - beforeUpdate header - beforeUpdate title - beforeUpdate list - beforeUpdate item-001 - beforeUpdate item-002 - beforeUpdate item-002 - updated item-001 - updated list - updated title - updated header - updated wrapper - updated page - updated

beforeUpdateupdated的触发顺序也是和beforeDestroydestroyed的一致。

Vue生命周期图示

lifecycle.png