原地址:vue -- 非父子組件傳值贱傀,事件總線(eventbus)的使用方式 - 積少成多 - CSDN博客
下面的組件A和組件B可以是項目中任意兩個組件
//在mian.js中
Vue.prototype.bus = new Vue()? //這樣我們就實現(xiàn)了全局的事件總線對象
//組件A中荞雏,監(jiān)聽事件
this.bus.$on('updata', function(data) {
? ? console.log(data)? //data就是觸發(fā)updata事件帶過來的數(shù)據(jù)
})
//組件B中,觸發(fā)事件
this.bus.$emit('updata', data)? //data就是觸發(fā)updata事件要帶走的數(shù)據(jù)
方式二创坞,稍微有點麻煩碗短,但也很容易理解
大概的實現(xiàn)思路: 新建一個bus.js文件, 在這個文件里實例化一下vue题涨;然后在組件A和組件B中分別引入這個bus.js文件偎谁,將事件監(jiān)聽和事件觸發(fā)都掛到bus.js這個實例上,這樣就可以實現(xiàn)全局的監(jiān)聽與觸發(fā)了
寫個例子
bus.js文件
// bus.js文件
import Vue from 'vue'
export default new Vue()
組件A
// 組件A 纲堵,監(jiān)聽事件send
<template>
? <div>
? ? <span>{{name}}</span>
? </div>
</template>
<script>
? import Bus from './bus.js'
? export default {
? ? data () {
? ? ? return {
? ? ? ? name: ''
? ? ? }
? ? },
? ? created() {
? ? ? let _this = this
? ? ? // 用$on監(jiān)聽事件并接受數(shù)據(jù)
? ? ? Bus.$on('send', (data) => {
? ? ? ? _this.name = data
? ? ? ? console.log(data)
? ? ? })
? ? },
? ? methods: {}
? }
</script>
組件B
// 組件B巡雨, 觸發(fā)事件send
<template>
? <div>
? ? <input type="button" value="點擊觸發(fā)" @click="onClick">
? </div>
</template>
<script>
? import Bus from './bus.js'
? export default {
? ? data () {
? ? ? return {
? ? ? ? elValue: '我是B組件數(shù)據(jù)'
? ? ? }
? ? },
? ? methods: {
? ? ? ? // 發(fā)送數(shù)據(jù)
? ? ? onClick() {
? ? ? ? Bus.$emit('send', this.elValue)
? ? ? }
? ? }
? }
</script>