JS listens for messages across labels

When it comes to opening multiple tab pages at the same time, operate a tab, and hope that other tabs will also update their status at the same time. You can use the following method to deal with

New crossTagMsg.js

Create a new crossTagMsg.js and write the following code

/**
 * 跨标签监听storage
 */

/**
 * 发送消息
 * @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)
}

how to use

When clicking to confirm adding or editing in the new tab, call the sendMsg method and pass two parameters, one is the message type and the other is the message content

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

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

Listen to the message in the mounted function of the original tag, and handle different operations according to the type value

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

mounted() {
    
    
  listenMsg((type, payload) => {
    
    
    console.log(type)
    console.log(payload)
    if (type === 'add') {
    
    
      this.tabData.push(payload.name)
    }
  })
},

achieve effect

Click the Add button in the new tab on the right, and the page data on the left tab page will be updated in real time

8558467.jpg

Guess you like

Origin blog.csdn.net/SongZhengxing_/article/details/128186423