1.0.0 • Published 1 year ago
common-event v1.0.0
前言
支持microp-app、qiankun2
无开发框架限制,支持Vue、React、原生JS等
安装
需将镜像切换至道丁库
// 切换镜像
npm config set registry http://dowding-npm.istarshine.net.cn/
npm install event-center --registry=http://dowding-npm.istarshine.net.cn/
或使用yarn
yarn add event-center --registry=http://dowding-npm.istarshine.net.cn/
框架
React/原生JavaScript
import { sendGlobal, send, listenGlobal, listen } from 'event-center'
// 然后直接使用相关方法即可
Vue
- 在入口文件(通常是main.js)中引入
// main.js
import { EventCenterVue } from 'event-center'
Vue.use(EventCenterVue)
// 通过this访问
this.$sendGlobal
this.$send
this.$listenGlobal
this.$listen
API及参数说明
- 内为可选参
- appName通常是微前端中所注册应用的名称
API | 功能描述 | 参数说明 |
---|---|---|
sendGlobal(eventName , data) | 发送到全局应用 | eventName: 必填,事件名称,stringdata: 可选,所发送的数据,any |
send(appName, eventName , data) | 发送到指定应用appName为数组时,同时向多个应用发送数据 | appName: 必填,接收此数据的应用名称,string | string[]eventName: 必填,事件名称data: 可选,所发送的数据 |
listenGlobal(eventName, cb) | 监听全局事件 | eventName: 必填,事件名称cb: 必填,监听事件的回调程序,该回调中可拿到所接收的数据 |
listen(appName, eventName, cb) | 监听指定应用事件 | appName: 必填,接收此数据的应用名称,string | string[]eventName: 必填,事件名称cb:必填,监听事件的回调程序,该回调中可拿到所接收的数据 |
示例
发送全局事件,并进行监听
// 应用A
sendGlobal('myEvent', 'helloWorld') // 发送自定义事件 myEvent, 携带数据 'helloWorld'
// 应用B、应用C内均可接受到
listenGlobal('myEvent', (data) => {
console.log(data) // 'helloWorld'
})
发送到指定应用,并在应用内监听
// 应用A
send('AppB', 'testEvent', 'helloWorld') // 发送自定义事件 testEvent到AppB, 携带数据 'helloWorld'
// 应用B
listen('AppB', 'testEvent', (data) => {
console.log(data) // 'helloWorld'
})
同时发送到多个指定应用
需查看注意事项
// 应用A
send(['AppB','AppC'], 'testEvent', 'helloWorld') // 发送自定义事件 testEvent到AppB和AppC, 携带数据 'helloWorld'
// 应用B
listen('AppB', 'testEvent', (data) => {
console.log(data) // 'helloWorld'
})
// 应用C
listen('AppC', 'testEvent', (data) => {
console.log(data) // 'helloWorld'
})
注意事项
send与listen支持同时向多个应用发送事件,因此可通过填入所有应用名称来实现全局发送效果,但其性能开销更大,建议使用sendGlobal与listenGlobal代替
应用间通信不进行隔离,因此,可在应用A内监听到发送给应用B的数据
参数appName相当于事件作用域,因此,可以在不同appName下使用相同的eventName
send('App1', 'event', data1) send('App2', 'event', data2) listen方法同上
1.0.0
1 year ago