如果父組件監聽到子組件掛載mounted做一些邏輯處理
1、使用on和emit
子組件emit觸發一個事件,父組件emit觸發一個事件,父組件on監聽相應事件,
// Parent.vue <Child @mounted="doSomething"/> // Child.vue mounted() { this.$emit("mounted"); }
2、hook鉤子函式
這里一種特別簡單的方式,子組件不需要任何處理,只需要在父組件參考的時候通過@hook來監聽即可,代碼重寫如下:
// Parent.vue <Child @hook:mounted="doSomething" ></Child> doSomething() { console.log('父組件監聽到 mounted 鉤子函式 ...'); }, // Child.vue mounted(){ console.log('子組件觸發 mounted 鉤子函式 ...'); }, // 以上輸出順序為: // 子組件觸發 mounted 鉤子函式 ... // 父組件監聽到 mounted 鉤子函式 ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/25021.html
標籤:JavaScript
下一篇:MVC 與 Vue
