安装
npm install mitt -S
新建一个工具类
import mitt from 'mitt'
const emitter = mitt()
export default emitter
// 工具类
组件中发送
<template>
<div>
<button @click="btn">发送消息</button>
<Event></Event>
</div>
</template>
<script setup>
import emitter from '../mitt/index.js'
import { ref } from 'vue'
import Event from '../components/eventbuss.vue'
const data = ref('1')
const btn = () => {
emitter.emit('data',data)
}
</script>
<style lang="scss" scoped>
</style>
组件中接收
<template>
<div>
<p v-for="item in data" :key="item">接收到的消息 {{ data }}</p>
</div>
</template>
<script setup>
import emitter from "../mitt";
import { ref } from 'vue'
let data = ref([])
emitter.on('data',(val) => {
data.value.push(val)
})
</script>
<style lang="scss" scoped>
</style>
在 Vue 中,EventBus 是一种事件总线机制,可以用于在不同组件之间进行通信。然而,如果你想要在不同路由页面之间传递值,使用 EventBus 可能并不是最佳的选择。