在开发一般的业务来说,不需要知道 Vue 中钩子函数过多的执行细节。但是如果你想写出足够稳健的代码,或者想开发一些通用库,那么就少不了要深入了解各种钩子的执行时机了。
组件生命周期 hook 在组件树中的调用时机
先直接看一个例子:
import Vue from 'vue';
Vue.component('Test', {
props: {
name: String
},
template: `
beforeCreate() {
console.log('Test beforeCreate');
},
created() {
console.log('Test created');
},
mounted() {
console.log('Test mounted');
},
beforeDestroy() {
console.log('Test beforeDestroy');
},
destroyed() {
console.log('Test destroyed');
},
beforeUpdate() {
console.log('Test beforeUpdate');
},
updated() {
console.log('Test updated');
}
});
Vue.component('Test1', {
props: {
name: String
},
template: '
beforeCreate() {
console.log('Test1 beforeCreate');
},
created() {
console.log('Test1 created');
},
mounted() {
console.log('Test1 mounted');
},
beforeDestroy() {
console.log('Test1 beforeDestroy');
},
destroyed() {
console.log('Test1 destroyed');
},
beforeUpdate() {
console.log('Test1 beforeUpdate');
},
updated() {
console.log('Test1 updated');
}
});
new Vue({
el: '#app',
data() {
return {
a: true,
name: ''
};
},
mounted() {
setTimeout(() =&