某些场景下需要完成夸标签页通信,比如,从列表页新开一个新增页面,新增完成后,需要更新列表页的数据。

util 封装

代码封装如下:

import { v4 as uuidV4 } from 'uuid';

// 特定前缀,避免 Storage 覆盖
const prefix = '@@';

export function trigger(type: string, payload: any) {
  localStorage.setItem(prefix + type, JSON.stringify({
    payload,
    temp: uuidV4()
  }));
}

export function on(type: string, handler: (value: any) => void) {
  const storageHandler = (e: StorageEvent) => {
    const { key, newValue } = e;
    if (key !== prefix + type) return;
    try {
      const payload = JSON.parse(newValue || '');
      handler(payload.payload);
    } catch (e) {
      console.warn('storage error with key of ', key);
    }
  };
  window.addEventListener('storage', storageHandler);
  return () => {
    window.removeEventListener('storage', storageHandler);
  }
}

使用

监听

// 需要注销监听时可以调用 off 函数
const off = on('a', (value) => {
    console.log(value);
});

触发

trigger('a', '急急急');