How does the vue project listen for localStorage or sessionStorage changes

  • 2021-10-16 00:43:55
  • OfStack

The cause of this problem: In an VUE page, two components are introduced, A component realizes basic information display, B component display list, I want to trigger the state through one button of A component, and then B component does business processing according to the state triggered by A component. First, I think of putting the state in localStorage, and then how to monitor the state of A component in B component

Solution:

1. First register a global method for Vue. protorype in main. js, then create an StorageEvent method, initialize events and dispatch them when I execute 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  Key 
 * @param { string } data  Data to store 
 * @returns 
 */
Vue.prototype.$addStorageEvent = function (type, key, data) {
  if (type === 1) {
    //  Create 1 A StorageEvent Events 
    var newStorageEvent = document.createEvent('StorageEvent');
    const storage = {
      setItem: function (k, val) {
        localStorage.setItem(k, val);
        //  Initialize the created event 
        newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
        //  Dispatch object 
        window.dispatchEvent(newStorageEvent);
      }
    }
    return storage.setItem(key, data);
  } else {
    //  Create 1 A StorageEvent Events 
    var newStorageEvent = document.createEvent('StorageEvent');
    const storage = {
      setItem: function (k, val) {
        sessionStorage.setItem(k, val);
        //  Initialize the created event 
        newStorageEvent.initStorageEvent('setItem', false, false, k, null, val, null, null);
        //  Dispatch object 
        window.dispatchEvent(newStorageEvent);
      }
    }
    return storage.setItem(key, data);
  }
}

There is also a simple package to monitor localStorage

2. Called in the A component-write to the cache


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

Or


this.resetSetItem('watchStorage', jsonObj);

3. Listening in the B component


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

Or


window.addEventListener('setItem', ()=> {
    this.newVal = sessionStorage.getItem('watchStorage');
    var data=JSON.parse(this.newVal)
     console.log(data)
})

These are the details of how the vue project listens for localStorage or sessionStorage changes. For more information about vue project listening for localStorage or sessionStorage, please pay attention to other related articles on this site!


Related articles: