Vue3中mitt使用

在Vue3中 o n , on, on,off和$once实例方法已被移除,在Vu3中可以使用Mitt库

1. 安装Mitt

npm install mitt -s

2. main.ts全局挂载

import { createApp } from 'vue'
import App from './App.vue'
import CardVue from './components/Card.vue'
import mitt from "mitt"

const Mitt = mitt()

export const app = createApp(App)

declare module 'vue'{
  export interface ComponentCustomProperties{
    $Bus: typeof Mitt
  }
}

app.config.globalProperties.$Bus = Mitt

app.mount('#app')
  1. 使用emit()派发事件 on()接受事件 off()事件移除 clear()情况所有
  • emit()派发事件
<template>
  <div>
    <div>我是A组件</div>
    <button @click="emit">B组件发送事件</button>
  </div>
</template>

<script setup lang=ts>
import {getCurrentInstance} from "vue"

const instance = getCurrentInstance()
const emit = ()=>{
  console.log("mitt");
  
  instance.proxy.$Bus.emit("on-xiaoman","A组件参数")
}

</script>
  • on()监听事件
<template>
  <div>
  </div>
</template>

<script setup lang=ts>

import { getCurrentInstance } from "vue"
const instance = getCurrentInstance()

instance.proxy.$Bus.on("on-xiaoman", (param) => {
  console.log("=======", param);

})


</script>

监听所有事件

instance?.proxy?.$Bus.on('*',(type,param)=>{
    console.log(type,param,'===========>B')
})
  • 移除监听事件
const Fn = (num: any) => {
    console.log(num, '===========>B')
}
instance?.proxy?.$Bus.on('on-num',Fn)//listen
instance?.proxy?.$Bus.off('on-num',Fn)//unListen
  • 情况所有监听
instance?.proxy?.$Bus.all.clear() 

你可能感兴趣的:(前端,vue.js,javascript,前端)