vue通过BroadcastChannel实现不同标签页直接传递消息

crossTagMsg.js

复制代码
const channel = new BroadcastChannel('demo');

export function sendMsg(type, content){
    channel.postMessage({
        type,
        content,
    });
}

export function listenMsg(callback){
    const handler = (e) => {
        callback && callback(e.data);
    }
    channel.addEventListener('message', handler);
    return() => {
        channel.removeEventListener('message', handler);
    };
}

A.vue发送消息页面

复制代码
import {listenMsg} from '@/utils/crossTagMsg'

function update(){
	sendMsg("更新", "dddd")
}

B.vue监听消息页面

复制代码
import {listenMsg} from '@/utils/crossTagMsg'

//监听消息
const cancelListen = listenMsg((msgInfo) => {
  console.log('监听到了更新', msgInfo)
})
//组件销毁时移除监听
onBeforeUnmount(cancelListen);
相关推荐
摘星编程28 分钟前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe55631 分钟前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
WHS-_-202244 分钟前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
摘星编程44 分钟前
React Native for OpenHarmony 实战:GestureResponderSystem 手势系统详解
javascript·react native·react.js
lili-felicity1 小时前
React Native for OpenHarmony 实战:加载效果的实现详解
javascript·react native·react.js·harmonyos
ChangYan.1 小时前
monorepo 多包管理识别不到新增模块,解决办法
前端·chrome
Jinuss1 小时前
React元素创建介绍
前端·react.js
济6171 小时前
linux 系统移植(第六期)--Uboot移植(5)--bootcmd 和 bootargs 环境变量-- Ubuntu20.04
java·前端·javascript
lili-felicity2 小时前
React Native for OpenHarmony 实战:Easing 动画完全指南
javascript·react native·react.js
m0_748254662 小时前
AJAX 基础实例
前端·ajax·okhttp