vue 项目中监听 localStorage 或 sessionStorage 的变化

出现这个问题的起因:在一个VUE页面中,引入两个组件,A组件实现基础信息展示,B组件展示列表,我要通过A组件的一个按钮触发状态,然后B组件根据A组件触发的状态来做业务处理,首先想到的是把状态放在localStorage,接下去就是在B组件怎么监听A组件状态

解决方法:

1.首先在 main.js 中给 Vue.protorype 注册一个全局方法,然后创建一个 StorageEvent 方法,当我在执行sessionStorage.setItem(k, val) 的时候,初始化事件并派发事件。

/**
 * @description
 * @author (Set the text for this tag by adding docthis.authorName to your settings file.)
 * @date 2019-05-29
 * @param { number } type 1 localStorage 2 sessionStorage
 * @param { string } key 键
 * @param { string } data 要存储的数据
 * @returns 
 */
Vue.prototype.$addStorageEvent = function (type, key, data) {
    if (type === 1) {
        // 创建一个StorageEvent事件
        var newStorageEvent = document.createEvent('StorageEvent');
        const storage = {
            setItem: function (k, val) {
                localStorage.setItem(k, val);
                // 初始化创建的事件
                newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
                // 派发对象
                window.dispatchEvent(newStorageEvent);
            }
        }
        return storage.setItem(key, data);
    } else {
        // 创建一个StorageEvent事件
        var newStorageEvent = document.createEvent('StorageEvent');
        const storage = {
            setItem: function (k, val) {
                sessionStorage.setItem(k, val);
                // 初始化创建的事件
                newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
                // 派发对象
                window.dispatchEvent(newStorageEvent);
            }
        }
        return storage.setItem(key, data);
    }
}

还有一个简单封装监听localStorage

Vue.prototype.resetSetItem = function (key, newVal) {
  if (key === 'watchStorage') {

      // 创建一个StorageEvent事件
      var newStorageEvent = document.createEvent('StorageEvent');
      const storage = {
          setItem: function (k, val) {
              sessionStorage.setItem(k, val);

              // 初始化创建的事件
              newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);

              // 派发对象
              window.dispatchEvent(newStorageEvent)
          }
      }
      return storage.setItem(key, newVal);
  }
}

2.在A组件中调用——写入缓存

this.$addStorageEvent(2, "user_info", data);

或者

this.resetSetItem('watchStorage', jsonObj);

3.在B组件中监听

window.addEventListener('setItem', (e) => {
     console.log(e);
});

或者

window.addEventListener('setItem', ()=> {
        this.newVal = sessionStorage.getItem('watchStorage');
        var data=JSON.parse(this.newVal)
         console.log(data)
})
原文地址:https://www.cnblogs.com/binmengxue/p/13920737.html