Vue3: mitt to get started quickly

Why use mitt?
Because vue3 has not provided a supporting event bus bus, you need to use the third-party library mitt to complete the things done by the bus in vue2

Step 1: Install mitt

npm install mitt

Step 2: Import mitt in the js file of the project (local registration)

// mitt.js文件
import mitt from 'mitt'

For global registration, add this code in mian.js

Step 3: Instantiate mitt. For easy understanding, we set the instance name as bus and expose it to the outside world

export const bus = mitt()

Step 4: Import bus in the vue file that needs to be used

import bus from './mitt'

Step 5: Use mitt's emit method to pass value and on method to receive data

// 父组件
bus.emit('函数名', 需要传的值)

//子组件
bus.on('函数名',(接收到的值)=>{
    
    
	逻辑操作
})

Guess you like

Origin blog.csdn.net/weixin_44001222/article/details/128179429