在Vue 3的入口文件(如main.js或main.ts)中,将Event Bus实例注册到全局属性上,以便在组件中访问: javascript // main.js import { createApp } from 'vue'; import App from './App.vue'; import emitter from './eventBus'; const app = createApp(App); // 全局注册Event Bus实例 app.config.globa...
import {getCurrentInstance} from 'vue' const instance = getCurrentInstance() // emit为自定义的发布事件,由于配置过类型提示,会出现 all | emit | on | clear // emit接受第一个参数为事件名(自定义),第二个参数为传递的值 const emit = () => { instance?.proxy?.emitter.emit('mitt-foo','...
TS版 const eventStack: any = {}; const $on = (eventName: string, callBack: (value: any) => void): void => { if (eventStack[eventName]) { eventStack[eventName].callBacks.push(callBack); callBack(eventStack[eventName].value); } else { console.error("该接口未注册,请先通过emit方...
import { ref, reactive, watch } from 'vue' const count = ref(0) const user = reactive({ name:'chengang', age: 28 }) // 监听基本数据类型 watch(() => count, (newval, oldval) => { console.log(newval, oldval) }) watch(() => count.value, (newval, oldval) => { consol...
在2.x,使用 EventBus 无需导入第三方插件,直接在自己的libs文件夹下创建一个bus.ts文件,暴露一个新的 Vue 实例即可。 import Vue from 'vue'; export default new Vue; 然后就可以在组件里引入 bus ,通过$emit去发起交流,通过$on去监听接收交流。
40 changes: 40 additions & 0 deletions 40 src/utils/eventBus.ts @@ -0,0 +1,40 @@ type EventType = string | symbol;type Handler<T = unknown> = (event: T) => void;function eventBus() { const all = new Map(); return { on(type: EventType, handler: Handler) {...
TS版 const eventStack: any = {}; const $on = (eventName: string, callBack: (value: any) => void): void => { if (eventStack[eventName]) { eventStack[eventName].callBacks.push(callBack); callBack(eventStack[eventName].value); ...
在2.x,使用 EventBus 无需导入第三方插件,直接在自己的libs文件夹下创建一个bus.ts文件,暴露一个新的 Vue 实例即可。 importVuefrom'vue';exportdefaultnewVue; 然后就可以在组件里引入 bus ,通过$emit去发起交流,通过$on去监听接收交流。 旧版方案的完整案例代码可以查看官方的2.x 语法 - 事件 API(opens ...