Vue中使用全局事件总线
使用第三方库mitt
实现全局事件总线,其原理,和Vue2类似,在app.config.globalProperties
上添加总线,然后在需要的组件中引入,调用其on/emit/off
等方法实现绑定、派发和解绑等操作
1、下载安装
npm i mitt
2、在main.ts
中配置
import { createApp } from 'vue'
import App from './App.vue'
// 引入mitt并初始化
import mitt from 'mitt'
const Mitt = mitt()
// 配置全局声明
declare module 'vue' {
export interface ComponentCustomProperties {
$bus: typeof Mitt
}
}
const app = createApp(App)
// 安装全局事件总线
app.config.globalProperties.$bus = Mitt
app.mount('#app')
3、使用
在需要使用事件总线的组件中引入并使用
A组件
<template>
<div class="A">
<h2>A组件</h2>
<h3>莫愁前路无知己,天下谁人不识君</h3>
<button @click="sendName">传递name给B组件</button>
<br />
<input type="text" v-model="name" placeholder="请输入name" />
</div>
</template>
<script setup lang="ts">
// 从全局获取事件总线
import { getCurrentInstance } from 'vue'
// 此处的$bus即为mitt提供的事件总线,名称与之前在main.ts中配置的一致
const $bus = getCurrentInstance()?.proxy?.$bus
const name = ref('默认值')
const sendName = () => {
// 调用emit方法触发名为'on-send-name'的自定义事件,传递数据
$bus?.emit('on-send-name', name.value)
}
</script>
B组件
<template>
<div class="B">
<h2>B组件</h2>
<h3>醉后不知天在水,满船清梦压星河</h3>
<h3>{{ name }}</h3>
</div>
</template>
<script setup lang="ts">
// 从全局获取事件总线
import { getCurrentInstance } from 'vue'
const $bus = getCurrentInstance()?.proxy?.$bus
const name = ref('这里接收A组件传递过来的name的值')
// 调用on方法为自定义事件'on-send-name'绑定回调函数,函数的参数就是要传递的数据
$bus?.on('on-send-name', (str: any) => {
name.value = str
})
</script>
4、结果
本文来自博客园,作者:光影星宸,转载请注明原文链接:https://www.cnblogs.com/gyxc/p/17324526.html