vue3.0 使用 mitt 事件总线
2022-04-25 本文已影响0人
如果俞天阳会飞
// main.ts
import mitt from 'mitt';
import App from './App.vue';
type Events = {
foo: string;
bar?: number;
};
const app = createApp(App);
app.config.globalProperties.$bus = mitt<Events>();
// child.vue
import { ref, getCurrentInstance, ComponentInternalInstance } from 'vue';
const medicineName = ref<string>('');
const { appContext } = getCurrentInstance() as ComponentInternalInstance;
appContext.config.globalProperties.$bus.on('medicineName', (name:string) => {
medicineName.value = name;
});
// emit.vue
import {
ref, getCurrentInstance, ComponentInternalInstance, defineEmits,
} from 'vue';
const { appContext } = getCurrentInstance()as ComponentInternalInstance;
appContext.config.globalProperties.$bus.emit('medicineName', '111111');