要在Vue 3 Composition API中使用事件总线, 请在main.js中使用Vue 3的新provideAPI,然后在任何组件中使用inject
yarn add mitt
import { createApp } from "vue";
import App from "./App.vue";
import mitt from 'mitt';
const emitter = mitt();
const app = createApp(App)
app.provide('emitter', emitter);
app.mount('#app');
import { inject } from 'vue'
export default {
setup() {
const emitter = inject("emitter");
emitter.on("hello", (value) => {
console.log(`App接收到的数据为:${value}`);
});
},
}
import { inject } from 'vue'
export default {
setup() {
const emitter = inject("emitter");
function show() {
emitter.emit("hello", "hello js");
}
return {
show,
};
},
};
App接收到的数据为:hello js
|