监听storage中数据的变化

方法封装:

updateStorage(name, value){
  sessionStorage.setItem('name, newVal);
      const storageEvent = new Event('storage');
      Object.defineProperty(storageEvent, 'key', {
        value: name,
        enumerable: true
      })
      Object.defineProperty(storageEvent, 'newValue', {
        value: newVal,
        enumerable: true
      })
      window.dispatchEvent(storageEvent)
}

使用:index.vue

 mounted() {
  window.addEventListener('storage', this.handleStorageEvent);
 },
 beforeDestroy() {
  window.removeEventListener('storage', this.handleStorageEvent);
 },
methods(){
    handleStorageEvent(event){
        if(event.key === 'latitude'){
            let data = event.newValue;
        }              
    }
}    

  

posted @ 2023-07-28 17:49  吃饭睡觉打痘痘  阅读(99)  评论(0编辑  收藏  举报