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
- Storage value: window.localStorage.setItem('key name', value)
- Read value: window.localStorage.getItem(''key name')
3. Monitor changes in localStorage values (take vue3 as an example)
- 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)
}
}
- Introduce and mount in main.ts
import dispatchEventStroage from './utils/watchLocalStorage'
app.use(dispatchEventStroage);
- 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对应的变化后的值。
}
})
})