前端实现跨标签页通信

前端实现跨标签页通信

在开发过程中,我们会遇到点击新增或者编辑,需要打开一个新页面进行操作,操作完成后,原来的页面不能自动更新,这时我们就需要使用标签页通信来自动更新原来的页面

新建 crossTabMsg.js,代码如下

// 引入BroadcastChannel, 用于跨标签通信
const channel = new BroadcastChannel('emp')

/**
 * 发送消息
 * @param {string} type 消息类型
 * @param msg 消息内容
 */
export function sendMsg(type, msg) {    
  channel.postMessage({
    type,
    msg,
  })
}

/**
 * 监听消息
 * @param callback 监听到消息时触发回调函数
 */
export function listenMsg(callback) {
  channel.addEventListener('message', e => {
    callback && callback(e.data)
  })
}

使用方法和简单,在需要发送消息的地方调用 sendMsg 方法即可,例如

submitForm(formName) {
    this.$refs[formName].validate((valid) => {
        if (valid) {
            if(this.form.id){
                this.$message({
                    message: "编辑成功",
                    type: "success",
                });
                sendMsg("edit", { ...this.form });
                window.close();
            }else{
                this.$message({
                    message: "新增成功",
                    type: "success",
                });
                sendMsg("add", { ...this.form, id: Date.now() });
                window.close();
            }
        } else {
            this.$message({
                message: "表单验证失败",
                type: "error",
            });
            return false;
        }
    });
}

在原来的页面中使用 listenMsg 方法监听消息,判断type的值进行不同的操作

mounted() {
    listenMsg((info) => {
        if (info.type === "add") {
            this.tableData.push(info.msg);
        } else if (info.type === "edit") {
            const index = this.tableData.findIndex((item) => item.id === parseInt(info.msg.id));
            this.tableData.splice(index, 1, info.msg);
        }
    });
}

最终实现效果如下

你可能感兴趣的:(echarts,javascript,前端)