utils/eventBus.js
import Vue from 'vue'
const Bus = new Vue()
export default Bus
/**
* 同级组件通讯,提交事件
* @param {String} component 要提交的目标组件名称
* @param {string} action 要调用目标组件的方法名
* @param {any} param 目标组件的方法参数
*/
export const BusEmit = (component, action, param) => {
Bus.$emit(component, action, param)
}
/**
* 同级组件通讯,监听销毁事件
*/
export const BusOn = {
mounted() {
Bus.$on(`${this.$options.name}`, this.onBusAction)
},
beforeDestroy() {
Bus.$off(`${this.$options.name}`, this.onBusAction)
},
methods: {
onBusAction(action, param) {
this[action](param)
},
},
}
定义2个组件
components/TianChou/index.vue
<template>
<div>A组件<el-button @click="tiaochouSay">发送</el-button></div>
</template>
<script>
import { BusEmit, BusOn } from '@/utils/eventBus'
export default {
name: 'TianChou',
mixins: [BusOn],
methods: {
tiaochouSay() {
BusEmit('PiaoPiao', 'piaopiaoListen', { msg: '不上班行不行' })
},
tiaochouListen(data) {
console.log('TianChou接收', data)
}
}
}
</script>
components/PiaoPiao/index.vue
<template>
<div>B组件<el-button @click="piaopiaoSay">发送</el-button></div>
</template>
<script>
import { BusEmit, BusOn } from '@/utils/eventBus'
export default {
name: 'PiaoPiao',
mixins: [BusOn],
methods: {
piaopiaoListen(data) {
console.log('PiaoPiao接收', data)
},
piaopiaoSay() {
BusEmit('TianChou', 'tiaochouListen', { msg: '不上班你养我啊' })
}
}
}
</script>
App.vue
<TianChou />
<PiaoPiao />
效果:
如果你觉得这篇文章对你有用,可以看看作者封装的库xtt-utils,里面封装了非常实用的js方法。如果你也是vue开发者,那更好了,除了常用的api,还有大量的基于element-ui组件库二次封装的使用方法和自定义指令等,帮你提升开发效率。不定期更新,欢迎交流~