一、EventBus是什么?
EventBus被称为事件总线,和Vuex类似。
实质上EventBus是一个不具备 DOM 的组件,它具有的仅仅只是它实例方法而已。
eventBus原理是创建一个空Vue实例, 然后在上面挂载通讯事件, 在响应事件时, 可以认为这个Vue实例(组件), 是所有组件的父组件, 在触发事件时, 可以认为这个Vue实例, 是所有组件的子组件
二、使用步骤
1.初始化
初始化有两种方式
1-1. bus.js按需加载
import Vue from 'vue';
let bus = new Vue();
export default bus;
1-2. 在main.js全局引入
Vue.prototype.$bus = new Vue();
2.发送数据
<template>
<div>
<div>
<el-button type="primary" @click="sendMsg">发送数据</el-button>
</div>
</div>
</template>
<script>
import bus from '../utils/bus'
export default {
data() {
return {
testBus:'你好呀,bus!',
}
},
methods: {
sendMsg() {
//通过触发$emit函数进行触发,发送数据
//第一个参数为事件名称
//第二个参数为传送的数据 注意要用this指定要发送的数据
bus.$emit('share', this.testBus) //使用第一种
// this.$bus.$emit('share', this.testBus) //使用第二种
}
}
</script>
3.接收数据
<template>
<div>{
{
receiveBus}}</div>
</template>
<script>
import bus from '../utils/bus'
export default {
data() {
return {
receiveBus :'',
}
},
created() {
//使用第一种
bus.$on('share', val => {
this.receiveBus = val
})
//使用第二种引入方式
// this.$bus.$on('share', val => {
// this.receiveBus = val
// })
},
}
</script>