4

Js跨标签页实时监听消息_利用localStorage事件来实现

 1 year ago
source link: https://www.fly63.com/article/detial/12288
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

当涉及到同时打开多个tab页,操作一个tab,希望其他的tab也会同时进行更新状态。就可以用下面的方法来处理

新建 crossTagMsg.js

新建 crossTagMsg.js,编写如下代码

/**
* 发送消息
* @param type 消息类型
* @param payload 消息内容
*/
export function sendMsg(type, payload) {
localStorage.setItem('@@' + type, JSON.stringify({
payload,
temp: new Date().getTime(), /*用时间戳避免发送重复消息时不会触发监听方法*/
}))
}

/**
* 监听消息
* @param handler 监听到后触发的回调操作
*/
export function listenMsg(handler) {
const storageHandler = e => {
const data = JSON.parse(e.newValue)
handler(e.key.substring(2), data.payload)
}
window.addEventListener('storage', storageHandler)
}

在新标签中点击确认新增或者编辑时,调用 sendMsg 方法,传递两个参数,一个是消息类型,一个是消息内容

import { sendMsg } from "../utils/crossTagMsg";

export default {
name: "test",
methods: {
changeStorage() {
sendMsg("add", {
name: 123123,
time: new Date().getTime()
})
}
}
}

在原标签的 mounted 函数中监听消息,可以根据 type 值来处理不同操作

import { listenMsg } from "../utils/crossTagMsg";

mounted() {
listenMsg((type, payload) => {
console.log(type)
console.log(payload)
if (type === 'add') {
this.tabData.push(payload.name)
}
})
},
来源:https://blog.csdn.net/SongZhengxing_/article/details/128186423

链接: https://www.fly63.com/article/detial/12288


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK