使用 React 生命周期函数 useEffect
来监听和处理 LocalStorage 的变化
javascript
import React, { useEffect } from 'react';
const LocalStorageListener = () => {
useEffect(() => {
// 注册监听器
const handleStorageChange = (event) => {
if (event.key === 'myKey') {
console.log('注册监听器', event.newValue);
}
};
// 添加监听器
window.addEventListener('storage', handleStorageChange);
// 触发监听器
const triggerCustomStorageEvent = () => {
const storageEvent = new StorageEvent('storage', {
key: 'myKey',
newValue: 'newValue',
url: window.location.href,
});
window.dispatchEvent(storageEvent);
};
// 移除监听器
return () => {
window.removeEventListener('storage', handleStorageChange);
};
}, []); // 空数组表示在组件挂载时运行
return (
<div>
<button onClick={() => localStorage.setItem('myKey', 'newValue')}>
修改 localStorage
</button>
<button onClick={() => window.dispatchEvent(new StorageEvent('storage', {
key: 'myKey',
newValue: localStorage.getItem('myKey'),
url: window.location.href,
}))}>
手动触发 StorageEvent
</button>
</div>
);
};
export default LocalStorageListener;
使用Vue生命周期钩子 onMounted
和 onUnmounted
来监听和处理 LocalStorage 的变化
javascript
<template>
<div>
<button @click="updateLocalStorage">修改 localStorage</button>
<button @click="triggerCustomStorageEvent">手动触发 StorageEvent</button>
</div>
</template>
<script lang="ts" setup>
import { onMounted, onUnmounted } from 'vue';
// 注册监听器
const handleStorageChange = (event: StorageEvent) => {
if (event.key === 'myKey') {
console.log('Detected localStorage change:', event.newValue);
}
};
const updateLocalStorage = () => {
localStorage.setItem('myKey', 'newValue');
};
// 触发监听器
const triggerCustomStorageEvent = () => {
const storageEvent = new StorageEvent('storage', {
key: 'myKey',
newValue: 'newValue',
url: window.location.href,
});
window.dispatchEvent(storageEvent);
};
// 添加监听器
onMounted(() => {
window.addEventListener('storage', handleStorageChange);
});
// 移出监听器
onUnmounted(() => {
window.removeEventListener('storage', handleStorageChange);
});
</script>