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

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)
})

以上就是vue 项目如何监听localStorage或sessionStorage的变化的详细内容,更多关于vue 项目监听localStorage或sessionStorage的资料请关注其它相关文章!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容