你真的了解Vue的生命周期吗?
相信熟悉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
中的数据。
那么,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的官方文档中也是有提及的。
嵌套组件中的生命周期钩子的触发顺序
嵌套结构:
输出结果:
beforeCreate
、created
、beforeMount
、mounted
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
可以看出,从beforeCreate
到beforeMount
是先从外层触发然后一层一层的往里层触发,而mounted
钩子则是里层先触发,然后再一层层往外层触发。
beforeDestroy
、destroyed
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
的触发顺序一致,也是从里层向外层触发,直接最外层卸载完毕,从而完成整个组件的卸载过程。
beforeUpdate
、updated
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
beforeUpdate
与updated
的触发顺序也是和beforeDestroy
与destroyed
的一致。