在Vue3中没有了EventBus兄弟组件通信,但是现在有了一个替代的方案mitt.js
,原理还是 EventBus
安装:
npm i mitt -S
方法一:像Vue2中bus.js
一样新建mitt.js
文件
mitt.js
import mitt from 'mitt'
const Mitt = mitt()
export default Mitt
//组件1
<template>
<button @click="sendMsg">传值</button>
</template>
<script>
import { defineComponent } from "vue";
import Mitt from './mitt.js'
export default defineComponent({
setup() {
const sendMsg = () => {
Mitt.emit('sendMsg','兄弟的值')
}
return {
sendMsg
}
},
});
</script>
//组件2
<template>
<div>
组件2
</div>
</template>
<script>
import { defineComponent, onUnmounted } from "vue";
import Mitt from './mitt.js'
export default defineComponent({
setup() {
const getMsg = (val) => {
console.log(val);//兄弟的值
}
Mitt.on('sendMsg', getMsg)
onUnmounted(() => {
//组件销毁 移除监听
Mitt.off('sendMsg', getMsg)
})
},
});
</script>
- setup语法糖
//组件1
<template>
<button @click="sendMsg">传值</button>
</template>
<script setup>
import Mitt from './mitt.js'
const sendMsg = () => {
Mitt.emit('sendMsg', '兄弟的值')
}
</script>
//组件2
<template>
<div>
组件2
</div>
</template>
<script setup>
import { onUnmounted } from "vue";
import Mitt from './mitt.js'
const getMsg = (val) => {
console.log(val);//兄弟的值
}
Mitt.on('sendMsg', getMsg)
onUnmounted(() => {
//组件销毁 移除监听
Mitt.off('sendMsg', getMsg)
})
</script>
方法二:像Vue2中bus.js
一样在 main.js 中注册挂载到全局
mport { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt'
import router from "./router";
const app = createApp(App)
// vue3挂载到全局
app.config.globalProperties.$mitt = mitt();
app.use(router).mount('#app')
组件1:
appContext.config.globalProperties.$mitt.emit('sendMsg', 兄弟的值);
组件1:
onMounted(() => {
appContext.config.globalProperties.$mitt.on('sendMsg', getMsg)
})
onUnmounted(() => {
appContext.config.globalProperties.$mitt.off('sendMsg');
});