比如有父組件 Parent 和子組件 Child,如果父組件監聽到子組件掛載 mounted 就做一些邏輯處理,可以通過以下寫法實現:
1 // Parent.vue 2 <Child @mounted="doSomething"/> 3 4 // Child.vue 5 mounted() { 6 this.$emit("mounted"); 7 }
以上需要手動通過 $emit 觸發父組件的事件,更簡單的方式可以在父組件引用子組件時通過 @hook 來監聽即可,如下所示:
1 // Parent.vue 2 <Child @hook:mounted="doSomething" ></Child> 3 4 doSomething() { 5 console.log('父組件監聽到 mounted 鈎子函數 ...'); 6 }, 7 8 // Child.vue 9 mounted(){ 10 console.log('子組件觸發 mounted 鈎子函數 ...'); 11 }, 12 13 // 以上輸出順序為: 14 // 子組件觸發 mounted 鈎子函數 ... 15 // 父組件監聽到 mounted 鈎子函數 ...
當然 @hook 方法不僅僅是可以監聽 mounted,其它的生命周期事件,例如:created,updated 等都可以監聽。