// 说明:跨系统或组件发送事件以及接收事件
1、建立工具文件
//dwj:写一个dispatchEvent派发事件
//dwj:进行事件的收集和派发到需要的事件
//键值对进行事件发送到浏览器缓存例如dwj发送99
//dwj:window.localStorage.setItem('dwj','99')
function dispatchEventItem () {
const signSetItem = localStorage.setItem
localStorage.setItem = function (key, val) {
let setEvent = new Event('setEventItem')
setEvent.key = key
setEvent.newValue = val
window.dispatchEvent(setEvent)
signSetItem.apply(this, arguments)
}
}
export default dispatchEventItem
2、main.j引入
import eventJs from '@/utils/eventJs'
Vue.use(eventJs)
3、发送事件
// 在需要发送的系统或组件进行发送
window.localStorage.setItem('dwj','99')
4、监听接收事件
// 接收系统或组件发送的事件
mounted(){
// mounted函数中进行事件的接收-只接收自己的值
window.addEventListener('setEventItem',function(e){
if(e.newValue=='刷新扣分'){
alert(e.newValue)
}
})
{