在vue中,
父與子元件溝通是透過props
傳值;
而子與父元件溝通則要透過event
來傳遞:
子元件可以發起一個客制化的event
($emit("customEvent", parm1, param2...)
再經由父元件handle即可:
<Child @customEvent="customEventHandler(param1, param2, ....)"></Child>
在vue的使用下,可能會有以下情形:需要溝通的元件是同層的元件,並且其上沒有父元件可以當溝通橋樑 (會有這個問題,是因為vue除了樹狀結構的virtual dom外,也可以使用全域component,將資料封裝在component中。)
之前網路上找到的解使用全域的mixin
,並且另外建一個eventHub vue Object 來解決問題:
const eventHub = new Vue(); // Single event hub
Vue.mixin({
data: function () {
return {
seesee: 0,
eventHub: eventHub,
isResult: false,
id: 0,
}
},
methods: {
toggleResultHandler(id) {
console.log(this.seesee)
console.log("toggle event",id)
console.log("fcuk you boy")
this.isResult = !this.isResult
}
},
created() {
this.seesee = ids;
ids = ids+1;
this.eventHub.$on("toggleResult", this.toggleResultHandler)
}
});
這樣子的實作方式會出問題。因為全域的mixin
會影響所有掛載的VUE元件。
舉例來說,如果你的元件中,使用一個table
元件,除此之外還有使用其它元件,
或者你使用別人寫的table
元件,其底下還有其它的子元件,
因為mixin
會影響所有的元件中,等於Vue會產生數個不同的eventHub。
這時如果你設定點選了某個資料,觸發event, 其實會有十個eventHub在等待handle event。
比較好的方式,應該使用Vue.prototype
注冊eventHub。
如此,可以確定eventHub是全域狀態外,
也不會發生像使用mixin方式造成多個eventHub的問題:
const eventHub = new Vue(); // Single event hub
Vue.prototype.eventHub = eventHub;
## 小心使用mixin全域 ##