面试提问:说说 vue 父子组件加载顺序
这我知道答案
- 父 beforeCreate
- 父 created
- 父 beforeMount
- 子 beforeCreate
- 子 created
- 子 beforeMount
- 子 mounted
- 父 mounted
子组件若有 props 的话更新顺序是四步,若无的话两步不触发父亲的钩子。
- 父 beforeUpdate
- 子 beforeUpdate
- 子 updated
- 父 updated
父组件更新顺序是
- 父 beforeUpdate
- 子 deactivated
- 父 updated
销毁过程是
- 父 beforeDestroy
- 子 beforeDestroy
- 子 destroyed
- 父 destroyed
再问,如果有多个子组件呢?我不太能确定。
加载多个子元素
回头写了一个简单的vue视图,父调用子,以下代码复制可用。
<!DOCTYPE html>
<html>
<head>
<title>Form Demo</title>
</head>
<body>
<div id="app">
<input-group :forms="forms" v-for="(forms, index) in options" :key="index"></input-group>
</div>
<!-- Vue.js v2.6.11 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component('input-group', {
props: ['forms'],
beforeCreate() {
console.log('child beforeCreate');
},
created() {
console.log('child created');
},
beforeMount() {
console.log('child beforeMount');
},
mounted() {
console.log('child mounted');
},
template: `<div>
<template v-for="item in forms">
<input type="text" v-model="item.data">
</template>
</div>`
})
let options = []
for (let i = 0; i < 2; i++) {
for (let j = 0; j < 2; j++) {
options[i] = options[i] || [];
options[i].push({
data: '',
})
}
}
var app = new Vue({
el: '#app',
beforeCreate() {
console.log('parent beforeCreate');
},
created() {
console.log('parent created');
},
beforeMount() {
console.log('parent beforeMount');
},
mounted() {
console.log('parent mounted');
},
data: {
options: options,
},
})
window.app = app;
console.log(app);
</script>
</body>
</html>
控制台打印结果如下
parent beforeCreate
parent created
parent beforeMount
child beforeCreate
child created
child beforeMount
child beforeCreate
child created
child beforeMount
(2) child mounted
parent mounted
能得出结论,第一个子元素在 beforeMount 后不会直接 mounted,而是进入下一个子元素的 beforCreate。