vue3 全局事件总线
1. 在main.js文件中定义$bus
与vue2不同的是,在vue3中不能直接使用
new Vue({
...
beforeCreate() {
Vue.prototype.$bus = this
}
}).$mount()
在vue3 则需要使用外部的、实现了事件触发器接口的库 mitt 和 tiny-emitter
我以 mitt 为例
(1) 安装
npm install mitt -s
(2)在main.js中引用
import mitt from "mitt"
(3)全局配置
const app = createApp(App)
app.mount('#app')
app.config.globalProperties.mittBus = new mitt()
2. 在组件中使用
import { getCurrentInstance } from "@vue/runtime-core"; // 引入getCurrentInstance
export default {
setup(props) {
let $bus = getCurrentInstance().appContext.config.globalProperties.$bus; // 声明$bus
$bus.emit("a", 我很帅!); // 发布事件
-----
$bus.on("a",我真的很帅!); // 订阅事件
$bus.off("a",...); //关闭订阅事件
return {
};
},
};
欢迎大家阅读,如有解释不当,请指出,互相学习,互相进步!