First of all, we have to download the mitt command as follows:
npm i mitt --save
Next, we will introduce two ways to use the event bus through mitt in Vue3
method one:
This method is to mount mitt globally. Personally, I feel a bit cumbersome and not recommended.
create:
1. First find your main.js or main.ts file
2. Introduce mitt
3. Mount mitt
As shown below:
code show as below:
import mitt from 'mitt'
// 通过mitt配置事件总线
const bus = mitt()
app.config.globalProperties.$bus = bus
use:
sender:
1. Introduce getCurrentInstance from vue
2. Get the bus just mounted
3. Send a custom event with parameters
code show as below:
import { getCurrentInstance } from "vue"
const ctx = getCurrentInstance()
const bus = ctx?.appContext.config.globalProperties.$bus
//自行定义
let a = ref<string>("你好")
bus.emit('sendToBrother', a)
receiver:
1. Introduce getCurrentInstance from vue
2. Get the bus just mounted
3. Listen to the custom events on the bus and obtain the parameters carried by the events
code show as below:
import { getCurrentInstance } from "vue"
const ctx = getCurrentInstance()
const bus = ctx?.appContext.config.globalProperties.$bus
// 如何接收,使用什么来接收请自行定义
let message = ref<string>("")
bus.on('sendToBrother', (data) => {
message.value = data.value
console.log(data.value);
})
Method 2:
This method is to create an additional bus.js file as the transfer of mitt, and import it directly from this file every time you use mitt
create:
1. Create a utils folder in the src directory
2. Create a bus.js file under the utils folder
3. Introduce mitt in the file and export
code show as below:
import mitt from 'mitt'
export const events = mitt()
use:
sender:
1. Introduce mitt
2. Send a custom event and carry parameters
code show as below:
import { events } from '../../utils/bus.js'
const bus = events
let a = ref<string>("你好")
// 触发发送自定义事件
const handleOneClick = () => {
bus.emit('sendToBrother', a)
}
receiver:
1. Introduce mitt
2. Listen to custom events on the bus and obtain the parameters carried by the event
code show as below:
import { events } from '../../utils/bus.js'
const bus = events
let message = ref<string>("")
bus.on('sendToBrother', (data) => {
message.value = data.value
console.log(data.value);
})