How to monitor the value change in localStorage in vue

1. Description

In daily development, we often use localStorage to store some variables. These variables are stored in the browser. For localStorage, even if the browser is closed, these variables are still stored, which is convenient for us to use in other places during development.

2. The use of localStorage

  1. Storage value: window.localStorage.setItem('key name', value)
  2. Read value: window.localStorage.getItem(''key name')

3. Monitor changes in localStorage values ​​(take vue3 as an example)

  1. Create a new file watchLocalStorage.ts in utils
export default function dispatchEventStroage() {
    
    
	const signSetItem = localStorage.setItem
	localStorage.setItem = function (key, val) {
    
    
		let setEvent = new Event('setItemEvent')
		setEvent.key = key
		setEvent.newValue = val
		window.dispatchEvent(setEvent)
		// eslint-disable-next-line prefer-rest-params
		signSetItem.apply(this, arguments)
	}
}
  1. Introduce and mount in main.ts
import dispatchEventStroage from './utils/watchLocalStorage'
app.use(dispatchEventStroage);
  1. where you need to monitor
// 监听localStorage中键名为tableData的变化
onMounted(() => {
    
    
	window.addEventListener('setItemEvent', function (e: any) {
    
    
		if (e.key === 'tableData') {
    
       // tableData 是需要监听的键名
			console.log(JSON.parse(e.newValue))   // 这里的newValue就是localStorage中,键名为tableData对应的变化后的值。
		}
	})
})

Guess you like

Origin blog.csdn.net/du_aitiantian/article/details/131481613