首先在main.js中给Vue.protorype注册一个全局方法,

其中,我们约定好了想要监听的sessionStorage的key值为’watchStorage’,

然后创建一个StorageEvent方法,当我在执行sessionStorage.setItem(k, val)这句话的时候,初始化事件,并派发事件。

 Vue.prototype.resetSetItem = function (key, newVal) {
   if (key === 'watchStorage') {
       var newStorageEvent = document.createEvent('StorageEvent');  // 创建一个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);
     }
  }
 如何触发
 在存储值的时候,使用下面的方法:
this.resetSetItem('watchStorage', JSON.stringify(obj1));
如果在另外一个路由(比如路由B)中,我们想根据watchStorage的变化来请求接口刷新页面数据的时候,可以在这个路由中created钩子函数中监听
    window.addEventListener('setItem', ()=> {
      this.radioCheckedItem = JSON.parse(sessionStorage.getItem('watchStorage'));
    })

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐