vue在main.js中eventHub

有時候在vue 中我們需要在不同的組件中傳值數據,大部分情況下我們可以store,或者可以使用inject 注入,又或者使用一個單獨得js,類似bus.js 。但是我們還是可以使用另外的一種bus。不過這個使用更加方便,而且不用新建文件。這個方法可以無視嵌套多少層級

主要的使用方法是在main.js中,在new Vue時候加上一個data的對象參數

➡️代碼示例:文件結構是index.vue父級,child1.vue子集,child1_1.vue孫級

1、在main.js中

new Vue({
  router,
  store,
  data:{
    eventHub:new Vue()
  },
  render: h => h(App)
}).$mount('#app')

2、index.vue文件

  1. 引入child1.vue文件和使用
      import child1 from './child1';

在creted中執行綁定的方法和methods設置對應的方法

	created() {
      this.$root.eventHub.$on('setEventHub',this.setEvent)
    },
    methods: {
      setEvent(msg){
        this.msg = msg
      }
    },

頁面上:

  <div>
    傳過來的值:{{msg}}
    <child1></child1>
  </div>

3、child1.vue

import child1_1 from './child1_1';

html(這裏頁面演示沒有其他內容,實際中我們是有內容的)

<child1_1></child1_1>

4、child1_1.vue

    methods: {
      useBusEvent(){
        this.$root.eventHub.$emit('setEventHub','這個是傳過來的')
      }
    }
<button @click="useBusEvent">使用busEvent</button>

5、結果:

在這裏插入圖片描述
單擊按鈕獲取值後:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章