vue3——全局事件总线(mitt)

安装mitt插件

npm i mitt --save

mitt使用

在src下新建bus文件夹,在该文件夹下新建index.ts
目录结构

index.ts 文件代码

import mitt from 'mitt';
const $bus = mitt();
export default $bus;

全局引入

在main.ts中引入

import { createApp } from 'vue'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

import App from './App.vue'
import router from '@/router'

// 引入mitt并挂载
import $bus from '@/bus';

const app = createApp(App);

// vue3的全局挂载方法方式
app.config.globalProperties.$bus = $bus;

app.use(ElementPlus);
app.use(router);

app.mount('#app');

使用

视图文件结构

event-bus代码
该文件用于展示兄弟组件传值,引入两个子组件

<template>
  <div class="event-bus">
    <h1>全局事件总线</h1>
    <div class="container">
        <Child1></Child1>
        <Child12></Child12>
    </div>
  </div>
</template>

<script lang='ts' setup>
import Child1 from './index.vue'
import Child12 from './index2.vue'
</script>
<style lang='scss' scoped>
.event-bus{
    background-color: #dca7a7;
    padding: 1rem;
    .container{
        display: flex;
        justify-content: space-between;
    }
}
</style>

child2组件向child组件传值
child2组件代码

<template>
  <div class="child2">
    <h3>子组件2</h3>
    <el-button @click="send">送兄弟一个对象</el-button>
  </div>
</template>

<script lang='ts' setup>
import { getCurrentInstance  } from "vue";
const {proxy} = getCurrentInstance() as any;
const send = ()=>{
    /**
   * @param {string} '' 事件类型,需与接收方一致
   * @param {function} () 回调
   */
  proxy?.$bus.emit('girlFriend',{
    name: '翠花',
    age: 18,
    sex: '女'
  })
}
</script>
<style lang='scss' scoped>
.child2{
  background-color: #e2e472;
  width: 300px;
  height: 300px;
}
</style>

child接收child2组件传来的值,需注意,事件类型要与发送方的名一致
child2组件代码

<template>
  <div class="child1">
    <h3>子组件1</h3>
    <p>姓名:{{ girlFriend.name }}</p>
    <p>性别{{ girlFriend.sex }}</p>
    <p>年龄{{ girlFriend.age }}</p>
  </div>
</template>
<script lang='ts' setup>
import { reactive, getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() as any;
// '对象'接口
interface GirlFriend {
  name: string
  age: number
  sex: string
}
let girlFriend = reactive<GirlFriend>({
  name: '',
  age: 0,
  sex: ''
});
/**
 * @param {string} '' 事件类型
 * @param {function} () 回调
 */
proxy?.$bus.on('girlFriend', (obj: GirlFriend) => {
  girlFriend = Object.assign(girlFriend,obj);
})

</script>
<style lang='scss' scoped>
.child1 {
  background-color: #72e4ab;
  width: 300px;
  height: 300px;
}
</style>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值