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);
相关推荐
遇到困难睡大觉哈哈4 小时前
Harmony os 静态卡片(ArkTS + FormLink)详细介绍
前端·microsoft·harmonyos·鸿蒙
用户47949283569155 小时前
Bun 卖身 Anthropic!尤雨溪神吐槽:OpenAI 你需要工具链吗?
前端·openai·bun
p***43485 小时前
前端在移动端中的网络请求优化
前端
g***B7385 小时前
前端在移动端中的Ionic
前端
大猩猩X5 小时前
vxe-gantt 甘特图使用右键菜单
vue.js·vxe-table·vxe-ui·vxe-gantt
拿破轮5 小时前
使用通义灵码解决复杂正则表达式替换字符串的问题.
java·服务器·前端
whltaoin5 小时前
【 Web认证 】Cookie、Session 与 JWT Token:Web 认证机制的原理、实现与对比
前端·web·jwt·cookie·session·认证机制
Aerelin6 小时前
爬虫playwright入门讲解
前端·javascript·html·playwright
笙年6 小时前
JavaScript Promise,包括构造函数、对象方法和类方法
开发语言·javascript·ecmascript
桜吹雪6 小时前
LangChain.js/DeepAgents可观测性
javascript·人工智能