转载:https://www.jianshu.com/p/f866c8ac4d02
const install = function (Vue) {
const Bus = new Vue({
methods: {
emit (event, ...args) {
this.$emit(event, ...args);
},
on (event, callback) {
this.$on(event, callback);
},
off (event, callback) {
this.$off(event, callback);
}
}
});
Vue.prototype.$bus = Bus;
};
export default install;
import VueBus from ‘./vue-bus‘
Vue.use(VueBus)
<template>
<div>
{{ number }}
<button @click="handleAddRandom">随机增加</button>
</div>
</template>
<script>
export default {
props: {
number: {
type: Number
}
},
methods: {
handleAddRandom () {
// 随机获取 1-100 中的数
const num = Math.floor(Math.random () * 100 + 1);
this.$bus.emit(‘add‘, num);
}
}
};
</script>
在index.vue 中使用counter组件并监听来自counter.vue的自定义事件
<template>
<div>
<h1>首页</h1>
随机增加:
<Counter :number="number"></Counter>
</div>
</template>
<script>
import Counter from ‘./counter.vue‘;
export default {
components: {
Counter
},
data () {
return {
number: 0
}
},
methods: {
handleAddRandom (num) {
this.number += num;
}
},
created () {
this.$bus.on(‘add‘, this.handleAddRandom);
},
beforeDestroy () {
this.$bus.off(‘add‘, this.handleAddRandom);
}
}
</script>
vue-bus的代码比较简单,但它却解决来跨组件直接的通信问题,而且通过插件的形式使用后,所有的组件都可以使用$bus,而无须每个组件导入bus组件,
实现非父子之间通信,兄弟组件之间的数据传递--eventBus
原文:https://www.cnblogs.com/web-record/p/12197737.html