vue兄弟元件event-bus通訊

FBI發表於2017-11-12

1. 思想

  • 使用一個空的 Vue 例項作為事件匯流排
  • 通過該空Vue例項來監聽和觸發事件

2.示例程式碼

以下程式碼基於vue-cli腳手架搭建

  • 如下程式碼示例,a和b元件作為兄弟元件在p元件引入
// p.vue
<template>
  <div>
    <p>bus</p>
    <aa></aa>
    <bb></bb> 
  </div>
</template>

<script>
 import aa from '@/components/a'
import bb from '@/components/b'
export default {
  components: {
    aa,
    bb
  }
} 
</script>複製程式碼
  • 在bus.js 中建立一個空的Vue例項
import Vue from 'vue'
export default new Vue()複製程式碼
  • a和b元件想通過bus通訊,則需引入bus.js 。要傳遞引數的元件,通過$on監聽自定義事件;要接受引數的元件,通過$emit 觸發自定義事件,並處理傳遞的引數。
// a.vue
<template>
  <div>
      元件a
      <button @click="sendMsg">問候元件b</button>
  </div>
</template>

<script>
import bus from './bus'
export default {
    methods: {
        sendMsg() {
            bus.$emit('send', '元件b你好嗎?')
        }
    }
}
</script>複製程式碼
// b.vue
<template>
    <div>        
        <p>元件b:{{ msg }}</p>
    </div>
</template>
<script>
import  bus  from './bus'
export default {
    data () {
        return {
            msg: 'msg初始值',
        }
    },
    created () {        
        bus.$on('send', data => {
            this.msg = data
        })
    }
}
</script>複製程式碼

相關文章