监听 localStorage 变化的技巧

使用自定义事件

  • 增强功能: 对于复杂应用,可以考虑通过发布/订阅模式或者自定义事件来管理和通知 localStorage 的变化。

  • 实现示例:

    const storageEvent = new Event('customLocalStorageChange');
     
    function updateLocalStorage(key, value) {
      localStorage.setItem(key, value);
      window.dispatchEvent(storageEvent);
    }
     
    window.addEventListener('customLocalStorageChange', () => {
      console.log('Custom event triggered for local storage change');
      // Custom handling logic here
    });
     
    updateLocalStorage('yourKey', 'newValue');