vue中如何监听localStorage中值的变化

一. 说明

在日常开发中,我们经常使用localStorage来存储一些变量。这些变量会存储在浏览中。对于localStorage来说,即使关闭浏览器,这些变量依然存储着,方便我们开发的时候在别的地方使用。

二. localStorage的使用

  1. 存储值:window.localStorage.setItem(‘键名’, 值)
  2. 读取值:window.localStorage.getItem('‘键名’)

三. 监听localStorage值的变化(以vue3为例)

  1. 在utils中新建一个文件watchLocalStorage.ts
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. 在main.ts中引入并挂载
import dispatchEventStroage from './utils/watchLocalStorage'
app.use(dispatchEventStroage);
  1. 在需要监听的地方
// 监听localStorage中键名为tableData的变化
onMounted(() => {
    
    
	window.addEventListener('setItemEvent', function (e: any) {
    
    
		if (e.key === 'tableData') {
    
       // tableData 是需要监听的键名
			console.log(JSON.parse(e.newValue))   // 这里的newValue就是localStorage中,键名为tableData对应的变化后的值。
		}
	})
})

猜你喜欢

转载自blog.csdn.net/du_aitiantian/article/details/131481613
今日推荐