vue3中如何监听本地存储的值
时间: 2025-06-23 12:27:13 浏览: 11
### Vue3 中监听 `localStorage` 的实现方法
#### 使用自定义 Hook 方式
为了更优雅地处理 `localStorage` 变化,在单页应用程序(SPA)环境中可以创建一个自定义 hook 来封装逻辑[^1]。
```javascript
// hooks/useLocalStorage.js
import { ref, onMounted, onUnmounted } from 'vue'
export default function useLocalStorage(key) {
const storageRef = ref(JSON.parse(window.localStorage.getItem(key)))
function updateStorage(value) {
window.localStorage.setItem(key, JSON.stringify(value))
storageRef.value = value
}
function handleStorageChange(event) {
if (event.key === key && event.storageArea === window.localStorage) {
try {
storageRef.value = JSON.parse(event.newValue)
} catch (_) {}
}
}
onMounted(() => {
window.addEventListener('storage', handleStorageChange)
})
onUnmounted(() => {
window.removeEventListener('storage', handleStorageChange)
})
return [storageRef, updateStorage]
}
```
此代码片段展示了如何通过组合 API 创建响应式的 `localStorage` 组件属性,并自动更新当检测到更改时。它还注册了一个事件监听器来捕获来自其他标签页或窗口中的变更通知。
#### 使用 Vuex Store 和 Watcher 方法
另一种常见的做法是在 Vuex store 中管理状态并利用 watcher 监视特定项的变化:
```typescript
// store/index.ts
import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";
const store = createStore({
state() {
return {
stationId: null,
};
},
mutations: {
setStationId(state, id) {
state.stationId = id;
},
},
});
createPersistedState({ paths: ["stationId"] })(store);
export default store;
// component.vue
<script setup>
import { watch } from "vue";
import { useStore } from "../store";
let store = useStore();
watch(
() => store.state.stationId,
(newValue, oldValue) => {
console.log(`stationId changed from ${oldValue} to ${newValue}`);
}
);
</script>
```
这种方法允许开发者集中管理和持久保存应用的状态,同时保持组件之间的解耦合性[^2]。
#### 添加全局事件监听器的方式
对于某些场景可能不需要复杂的依赖注入机制;可以在任何地方简单添加对 `'storage'` 事件的侦听即可满足需求:
```javascript
// main.js or specific component
import { ref, onMounted } from 'vue';
function listenToLocalStorageItem(itemKey) {
let itemValue = ref(localStorage.getItem(itemKey));
onMounted(() => {
window.addEventListener('storage', ({key, newValue}) => {
if (key === itemKey){
itemValue.value = newValue ?? localStorage.getItem(itemKey);
}
});
});
return itemValue;
}
// Usage example inside a SFC script tag with <script setup> syntax
const curr = listenToLocalStorageItem('curr');
console.log(curr.value); // Logs the current value of 'curr'
```
这种方式适用于那些只需要关注某个具体键值变动而不必引入额外库的情况[^3]。
阅读全文
相关推荐


















