useLocalStorage组合函数封装localStorage读写逻辑,支持响应式、类型安全、错误降级与SSR兼容。
在组合式函数中管理本地存储(localStorage)数据,核心是把读写逻辑封装成可复用、响应式、带错误处理的函数,同时避免硬编码键名和手动同步状态。
不要在每个组件里重复写 localStorage.getItem 和 setItem。直接封装一个组合函数,比如 useLocalStorage:
用 ref 包裹值,确保模板和逻辑能响应变化;同时用 watch 监听 ref 更新并写入 localStorage:
JSON.stringify(newVal) !== JSON.stringify(oldVal)),防止重复序列化if (typeof window !== 'undefined') 判断配合 TypeScript 使用泛型,让返回的 ref 具备明确类型:
function useLocalStorage<T>(key: string, defaultValue: T): Ref<T>
比如保存用户主题偏好:
在composables/useTheme.ts 中:
import { ref, watch, onMounted } from 'vue'export function useTheme() {
const theme = useLocalStorage<string>('app-theme', 'light')
const toggle = () => { theme.value = theme.value === 'light' ? 'dark' : 'light' }
return { theme, toggle }
}
组件中直接解构使用,修改 theme.value 就会自动持久化。