前言
最近看到别人的 后台管理系统 做了这样一个功能:
- 当在列表页时,点击列表对应的修改按钮,浏览器打开一个新的 tab 页
- 在新的 tab 页上是一个详情页,当修改里面的详情数据后,点击提交
- 列表页当发现详情页面提交后,会重新请求数据
感觉这个功能很有趣,找了几个比较好的方案,做一个记录
storage
storage
可以跨页面触发事件,下面是 MDN
关于 storageEvent 的介绍

所以我们可以根据 storage
的这个特性来做
我们使用一个按钮模拟 列表页面的修改按钮

点击这个按钮,跳转到 详情页面
使用 window.open 可以打开一个新的 tab,使用 vue-router 只能在页面内跳转
js
doClick() {
window.open("http://localhost:8080/detail", "_blank")
}
在 mounted
中编写监听函数
js
window.addEventListener('storage', function (event) {
if (event.key === 'shareData') {
const newData = event.newValue;
console.log('收到的更新数据:', newData);
}
});
在详情页面,我们使用 input
表示详情 form, 一个按钮表示 提交

在修改中只需使用 storage 保存输入框里面的值即可(输入框已经使用v-model绑定在变量num上)
js
change() {
localStorage.setItem('shareData', this.num);
}
当点击修改时,可以看到 列表中的监听函数生效

这个 this.num
只是模拟,实际上只要 stoage
不重复即可触发监听,等触发监听后就可以重新发起请求
BroadcastChannel
BroadcastChannel是一个专门跨标签通信的解决办法

核心在于两个 tab 使用同一个 BroadcastChannel
实例
新建 BroadcastChannel.js
,目的是为了多个 tab 使用同一个实例
js
const channelObj = new BroadcastChannel('BroadcastChannel');
export {
channelObj
}
在列表页中的 mounted
函数中监听
js
import {channelObj} from "./BroadcastChannel"
channelObj.addEventListener("message", function (event) {
const newData = event.data;
console.log('收到的更新数据:', newData);
})
我们在详情页面使用 postMessage
发送消息
js
import {channelObj} from "./BroadcastChannel"
change() {
// 发送消息
channelObj.postMessage(this.num);
}
同样的也可以收到更新后的数据,和 storage 不同的是,this.num
可以为相同的值

结尾
今天介绍两种 vue 的跨标签通信,如果有什么其他的好的跨标签通信,会再次更新