SoFunction
Updated on 2025-04-10

Solution to JavaScript custom localStorage listening events

1. Problem

During the project development process, I found that there are many times()After setting local storage, the page must be refreshed to obtain the stored data. Sometimes, after the local cache is updated, the page cannot obtain the local cache by refreshing again, which causes the data that depends on the local cache to be unable to be updated. To solve this problem, customization must be usedlocalStorageListen to events

2. Solution

The following is a customization using the Vue3 project as an examplelocalStorageExplanation of the monitoring event method.

first, in the root directorysrcCreated in the directoryutilsFolder, inutilsAdded in folderThe file content is as follows:

// 

// Rewrite the setItem event. When using setItem, trigger and dispatch eventsexport function dispatchEventStroage () {
    const signSetItem = 
     = function (key, val) {
      let setEvent = new Event('setItemEvent')
       = key
       = val
      (setEvent)
      (this, arguments)
    }
  }
  

Next, in the entry file of the projectIntroduce a custom rewrite method

1. Methods for introducing files

import {dispatchEventStroage} from "./utils/overwrite"

2. Use it globally.

dispatchEventStroage()

3. CompleteThe examples introduced, if you have any unclear areas, please refer to the complete one below.Example:

import {createApp} from 'vue'
import './'
import App from './'
import router from './router'
import {createPinia} from 'pinia'
import screenShort from "vue-web-screen-shot";
import {dispatchEventStroage} from "./utils/overwrite"

const app = createApp(App)

dispatchEventStroage()

(router)
(createPinia())
(screenShort, {enableWebRtc: true})
('#app')

at last, use it where needed, the usage examples are as follows:

('setItemEvent', (e) => {
      ("The event was triggered",e)
  })

This is the article about the solution to JavaScript custom localStorage listening events. For more information about JS custom localStorage listening events, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!