免费刷粉网站推广,小游戏网址代码,五屏网站建设平台,小程序推广话术案例在 Vue3 中#xff0c;$on#xff0c;$off 和 $once 实例方法被移除#xff0c;EventBus 无法使用了。那么此时#xff0c;我们可以使用 Mitt 库#xff08;发布订阅模式的设计#xff09;。
// 安装 mitt
npm install mitt -S// main.ts
import { createApp } from vue…在 Vue3 中$on$off 和 $once 实例方法被移除EventBus 无法使用了。那么此时我们可以使用 Mitt 库发布订阅模式的设计。
// 安装 mitt
npm install mitt -S// main.ts
import { createApp } from vue
import App from ./App.vue
import mitt from mitt
const app createApp(App)
const Mit mitt()
declare module vue {export interface ComponentCustomProperties {$Bus: typeof Mit}
}
app.config.globalProperties.$Bus Mit
app.mount(#app)!-- App.vue --
templatedivA/AB/B/div
/templatescript setup langts
import { reactive, ref } from vue;
import A from ./components/A.vue;
import B from ./components/B.vue;
/scriptstyle scoped langless/style!-- A.vue --
templatedivh1我是A组件/h1button clickemitemit/buttonhr/div
/templatescript setup langts
import { getCurrentInstance } from vue;
const instance getCurrentInstance();
const emit () {
instance?.proxy?.$Bus.emit(a, 我是A组件)instance?.proxy?.$Bus.emit(a1, 我是A1组件)
}
/scriptstyle scoped/style
!-- B.vue --
templatedivh1我是B组件/h1/div
/templatescript setup langts
import { getCurrentInstance } from vue
const instance getCurrentInstance()
instance?.proxy?.$Bus.on(a, (str) {console.log(str, B 组件);
})
// * 代表监听所有事件触发
instance?.proxy?.$Bus.on(*, (type, str) {console.log(type, str, B 组件);
})
/scriptstyle scoped/style还有一些其他方法
!-- B.vue --
templatedivh1我是B组件/h1/div
/templatescript setup langts
import { getCurrentInstance } from vue
const instance getCurrentInstance()
const Bus (str: any) {console.log(str, B 组件);
}
instance?.proxy?.$Bus.on(a, Bus)
instance?.proxy?.$Bus.off(a, Bus) // 删除该事件
instance?.proxy?.$Bus.all.clear() // 删除所有事件
/scriptstyle scoped/style