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