所以,你是知道怎么監(jiān)聽(tīng)LocalStorage的變化的?
前言
大家好,我是林三心,用最通俗易懂的話講最難的知識(shí)點(diǎn)是我的座右銘,基礎(chǔ)是進(jìn)階的前提是我的初心
背景
前幾天有位兄弟問(wèn)我,如何去監(jiān)聽(tīng)localStorage的變化呢??我確實(shí)是沒(méi)遇到過(guò)這種場(chǎng)景,但是我仔細(xì)想想,似乎想要達(dá)到這樣的效果,其實(shí)也不難。
解題思路
第一種:storageEvent
其實(shí)JavaScript原生就有一個(gè)監(jiān)聽(tīng)localStorage變化的事件——storage,使用方法如下
window.addEventListener('storage', () => {
  // callback
})我們來(lái)看看MDN上是怎么描述這個(gè)事件的:

也就是說(shuō),同域下的不同頁(yè)面A、B,只有本頁(yè)面修改了localStorage才會(huì)觸發(fā)對(duì)方的storage事件
但是顯然這種方案很不適用在現(xiàn)在的大部分項(xiàng)目中,畢竟這種方案太局限了,不能應(yīng)用在本頁(yè)面監(jiān)聽(tīng)的場(chǎng)景
第二種:封裝localStroage
其實(shí)就是代理一下對(duì)localStorage進(jìn)行多一層的封裝,使得我們每次在操作localStorage的時(shí)候,都會(huì)多走一層函數(shù),而我們就可以在這一層中去執(zhí)行監(jiān)聽(tīng)的事件了,下面是簡(jiǎn)單的代碼例子:
class CommonLocalStorage {
  private storage: Storage;
  constructor() {
    this.storage = window.localStorage;
  }
  set(key: string, value: any) {
    // 執(zhí)行監(jiān)聽(tīng)的操作
    return this.storage.setItem(`${prefix}${key}`, value);
  }
  get(key: string) {
    // 執(zhí)行監(jiān)聽(tīng)的操作
    return this.storage.getItem(`${prefix}${key}`);
  }
  del(key: string) {
    // 執(zhí)行監(jiān)聽(tīng)的操作
    return this.storage.removeItem(`${prefix}${key}`);
  }
  clear() {
    // 執(zhí)行監(jiān)聽(tīng)的操作
    this.storage.clear();
  }
}
const commonStorage = 
new CommonLocalStorage();
export default commonStorage這種方式也被應(yīng)用于很多比較出名的項(xiàng)目中,大家可以去看那些開源的項(xiàng)目中,基本很少直接使用localStorage,而是都是會(huì)封裝一層的















 
 
 















 
 
 
 