面试提问:说说 vue 父子组件加载顺序
这我知道答案
子组件若有 props 的话更新顺序是四步,若无的话两步不触发父亲的钩子。
父组件更新顺序是
销毁过程是
再问,如果有多个子组件呢?我不太能确定。
回头写了一个简单的vue视图,父调用子,以下代码复制可用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<!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> |
控制台打印结果如下
1 2 3 4 5 6 7 8 9 10 11 |
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。
from:https://www.cnblogs.com/everlose/p/12538472.html