【Mitt 全局使用、按需使用】

下载 Mitt 依赖:
npm install mitt -S

1、全局引入:

 1、main.ts中引入
import { createApp } from 'vue'
import App from './App.vue'
import mitt from 'mitt'
export const app = createApp(App)
const Mit = mitt()
declare module 'vue' {
  export interface ComponentCustomProperties {
    $Bus: typeof Mit
  } 
}
app.config.globalProperties.$Bus = Mit
app.mount('#app')
 2、使用展示
(1)传递值
<template>
    <div>
        <h1>传递值组件</h1>
        <div @click="emitClick">点击传递值</div>
    </div>
</template>
<script setup lang="ts">
// 传递值组件
import { getCurrentInstance } from 'vue'
const Instance = getCurrentInstance()
const emitClick = () => {
  Instance?.proxy?.$Bus.emit('emitData' , '传输过去的值')
}
</script>
(2)接收值(接收指定事件传递值)
<template>
    <div>
        <h1>接收值组件</h1>
    </div>
</template>
<script setup lang="ts">
// 接收值组件 接收单个指定事件传递过来的值
import { getCurrentInstance } from 'vue';
const Instance = getCurrentInstance()
Instance?.proxy?.$Bus.on('emitData' , (value) => {
    console.log(value , '接收传递过来的值')
})
</script>
(3)接收值(接收多个事件传递值) 
<template>
    <div>
        <h1>接收值组件</h1>
    </div>
</template>
<script setup lang="ts">
// 接收值组件 接收多个事件传递过来的值
import { getCurrentInstance } from 'vue';
const Instance = getCurrentInstance()
Instance?.proxy?.$Bus.on('*' , (type , value) => {
    // type 为事件名称
    // value 为每个事件对应的传递值
    console.log(type , value , '接收多个事件传递过来的值')
})
</script>
(4)清除值 (清除所有和单个事件清除)
// 清除所有
instance?.proxy?.$Bus.all.clear()
// 清除指定传递事件
instance?.proxy?.$Bus.off('需要清除的事件名', (value) => {
    console.log(value, '事件消除')
})

2、按需引入(推荐使用)

 1、创建一个Bus.ts文件
import mitt from 'mitt'
const Mit = mitt()
export default Mit
 2、传递值
<template>
    <div>
        <h1>传递值组件</h1>
        <div @click="emitClick">点击传递值</div>
    </div>
</template>
<script setup lang="ts">
// 传递值组件
import Mit from 'Bus文件路径'
const emitClick = () => {
  Mit.emit('自定义事件名称' , '需要传递的值')
}
</script>
  3、接收值
<template>
    <div>
        <h1>接收值组件</h1>
    </div>
</template>
<script setup lang="ts">
// 接收值组件 接收多个事件传递过来的值
import Mit from 'Bus.ts文件路径'
// 接收指定事件传递的值
Mit.on('指定事件名称' , (value) => {
  console.log(value)
})
// 接收所有的事件传递的值
Mit.on('*' , (type , value) => {
    // type 为事件名称
    // value 为每个事件对应的传递值
    console.log(type , value , '接收多个事件传递过来的值')
})
</script>
  4、清除传递值 
// 清除所有
Mit.all.clear()
// 清除指定传递事件
Mit.off('需要清除的事件名', (value) => {
    console.log(value, '事件消除')
})

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值