Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. # child-parent comunication #
  2.  
  3. 在vue中,
  4. 父與子元件溝通是透過`props`傳值;
  5. 而子與父元件溝通則要透過`event`來傳遞:
  6. 子元件可以發起一個客制化的`event`(`$emit("customEvent", parm1, param2...)`
  7. 再經由父元件handle即可:
  8. `<Child @customEvent="customEventHandler(param1, param2, ....)"></Child>`
  9.  
  10. 在vue的使用下,可能會有以下情形:需要溝通的元件是同層的元件,並且其上沒有父元件可以當溝通橋樑
  11. (會有這個問題,是因為vue除了樹狀結構的virtual dom外,也可以使用全域component,將資料封裝在component中。)
  12.  
  13. 之前網路上找到的解使用全域的`mixin`,並且另外建一個eventHub vue Object 來解決問題:
  14.  
  15. ```javascript
  16. const eventHub = new Vue(); // Single event hub
  17. Vue.mixin({
  18. data: function () {
  19. return {
  20. seesee: 0,
  21. eventHub: eventHub,
  22. isResult: false,
  23. id: 0,
  24. }
  25. },
  26. methods: {
  27. toggleResultHandler(id) {
  28. console.log(this.seesee)
  29. console.log("toggle event",id)
  30. console.log("fcuk you boy")
  31. this.isResult = !this.isResult
  32. }
  33. },
  34. created() {
  35. this.seesee = ids;
  36. ids = ids+1;
  37. this.eventHub.$on("toggleResult", this.toggleResultHandler)
  38. }
  39. });
  40. ```
  41.  
  42. 這樣子的實作方式會出問題。因為全域的`mixin`會影響所有掛載的VUE元件。
  43. 舉例來說,如果你的元件中,使用一個`table`元件,除此之外還有使用其它元件,
  44. 或者你使用別人寫的`table`元件,其底下還有其它的子元件,
  45. 因為`mixin`會影響所有的元件中,等於Vue會產生數個不同的eventHub。
  46.  
  47. 這時如果你設定點選了某個資料,觸發event,
  48. 其實會有十個eventHub在等待handle event。
  49.  
  50. 比較好的方式,應該使用`Vue.prototype`注冊eventHub。
  51. 如此,可以確定eventHub是全域狀態外,
  52. 也不會發生像使用mixin方式造成多個eventHub的問題:
  53.  
  54. ```javascript
  55. const eventHub = new Vue(); // Single event hub
  56. Vue.prototype.eventHub = eventHub;
  57. ```
  58.  
  59. ## 小心使用mixin全域 ##
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement