Vue3项目中实现localStorage实时监听的工程化实践
在构建现代单页应用时,我们经常需要依赖localStorage来存储用户偏好、登录状态或应用配置。然而,一个长期困扰开发者的痛点在于:当localStorage中的数据发生变化时,应用无法自动感知并更新相关状态。想象一下这样的场景:用户在另一个标签页修改了主题设置,但当前页面仍然显示旧的样式,直到手动刷新才生效。这种体验上的割裂感,正是我们需要解决的核心问题。
传统的解决方案往往依赖于轮询检查或手动触发更新,这不仅效率低下,还会增加代码的复杂性。随着Vue3 Composition API的普及,我们有了更优雅的方式来封装这类跨组件、跨页面的状态同步逻辑。本文将带你深入探索如何在Vue3项目中构建一个健壮、类型安全且高度可复用的localStorage监听系统,涵盖从基础原理到生产级实现的全过程。
1. 理解localStorage监听的核心机制
在深入代码实现之前,我们需要先理清localStorage监听的技术基础。浏览器提供了两种不同粒度的监听机制,它们适用于不同的场景,理解这些差异是构建正确解决方案的前提。
1.1 跨标签页监听:storage事件
浏览器原生支持storage事件,这是监听localStorage变化最直接的方式。但这个机制有一个重要的限制:它只在其他标签页或窗口修改localStorage时触发,当前标签页自身的修改不会触发该事件。
// 基础的事件监听示例
window.addEventListener('storage', (event) => {
console.log('存储发生变化:', {
key: event.key, // 发生变化的键名
oldValue: event.oldValue, // 变化前的值
newValue: event.newValue, // 变化后的值
url: event.url, // 触发变化的页面URL
storageArea: event.storageArea // 存储区域对象
});
});
注意:
storage事件只在同源(相同协议、域名、端口)的不同页面间有效。如果修改来自同一页面,事件不会被触发,这是浏览器出于性能考虑的设计决策。
1.2 当前页面监听:重写与代理
对于当前页面的localStorage修改,浏览器没有提供原生的事件机制。这就需要我们采用一些"技巧"来实现监听。主要有两种主流方案:
方案一:重写原生方法
通过重写localStorage.setItem等方法,在调用时派发自定义事件:
const originalSetItem = localStorage.setItem;
localStorage.setItem = function(key, value) {
// 创建并派发自定义事件
const event = new CustomEvent('localStorageChange', {
detail: { key, newValue: value, oldValue: localStorage.getItem(key) }
});
window.dispatchEvent(event);
// 调用原始方法
return originalSetItem.apply(this, arguments);
};
方案二:使用Proxy代理 ES6的Proxy提供了更优雅的拦截机制:
const localStorageProxy = new Proxy(localStorage, {
set(target, prop, value) {
const oldValue = target.getItem(prop);
const result = target.setItem(prop, value);
// 触发自定义事件
window.dispatchEvent(new CustomEvent('localStorageChange', {
detail: { key: prop, newValue: value, oldValue }
}));
return result;
}
});
这两种方案各有优劣。重写方法更直接,但可能与其他库冲突;Proxy方案更现代,但需要考虑浏览器兼容性。在实际项目中,我们通常会结合使用,以覆盖所有可能的修改场景。
2. 构建类型安全的Vue3 Composition Hook
Vue3的Composition API为我们提供了完美的抽象工具。我们可以创建一个自定义Hook,将localStorage的监听逻辑封装起来,提供类型安全、响应式的API。
2.1 基础Hook实现
让我们从最基础的实现开始,逐步添加高级功能:
// types/localStorage.ts - 类型定义
export interface StorageEventDetail {
key: string;
newValue: string | null;
oldValue: string | null;
storageArea: Storage;
}
export interface UseLocalStorageOptions<T = any> {
defaultValue?: T;
listenToCurrentTab?: boolean;
debounceDelay?: number;
serializer?: (value: T) => string;
deserializer?: (value: string) => T;
}
// hooks/useLocalStorage.ts
import { ref, watch, onUnmounted } from 'vue';
import type { Ref } from 'vue';
export function useLocalStorage<T = any>(
key: string,
options: UseLocalStorageOptions<T> = {}
): Ref<T> {
const {
defaultValue,
listenToCurrentTab = true,
debounceDelay = 300,
serializer = JSON.stringify,
deserializer = JSON.parse
} = options;
// 初始化值
const initialValue = (() => {
const stored = localStorage.getItem(key);
return stored !== null ? deserializer(stored) : defaultValue;
})();
const value = ref<T>(initialValue) as Ref<T>;
// 防抖函数
let debounceTimer: number | null = null;
const debounce = (fn: Function) => {
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(fn, debounceDelay);
};
// 监听storage事件(跨标签页)
const handleStorageEvent = (event: StorageEvent) => {
if (event.key === key && event.storageArea === localStorage) {
debounce(() => {
const newValue = event.newValue !== null
? deserializer(event.newValue)
: defaultValue;
value.value = newValue;
});
}
};
// 监听当前页面的修改
const handleLocalChange = (event: CustomEvent<StorageEventDetail>) => {
if (event.detail.key === key) {
debounce(() => {
const newValue = event.detail.newValue !== null
? deserializer(event.detail.newValue)
: defaultValue;
value.value = newValue;
});
}
};
// 设置事件监听
window.addEventListener('storage', handleStorageEvent);
if (listenToCurrentTab) {
window.addEventListener('localStorageChange', handleLocalChange as EventListener);
}
// 监听value变化并更新localStorage
watch(value, (newVal) => {
localStorage.setItem(key, serializer(newVal));
}, { deep: true });
// 清理
onUnmounted(() => {
window.removeEventListener('storage', handleStorageEvent);
if (listenToCurrentTab) {
window.removeEventListener('localStorageChange', handleLocalChange as EventListener);
}
});
return value;
}
这个基础版本已经具备了核心功能,但还缺少对当前页面修改的监听支持。接下来我们需要实现这个关键部分。
2.2 实现当前页面监听器
为了监听当前页面的修改,我们需要重写localStorage的方法。但要注意避免与其他库冲突:
// utils/localStorageMonitor.ts
let isPatched = false;
export function patchLocalStorage() {
if (isPatched) return;
const originalMethods = {
setItem: localStorage.setItem,
removeItem: localStorage.removeItem,
clear: localStorage.clear
};
// 重写setItem
localStorage.setItem = function(key: string, value: string) {
const oldValue = localStorage.getItem(key);
const result = originalMethods.setItem.call(this, key, value);
// 派发自定义事件
window.dispatchEvent(new CustomEvent('localStorageChange', {
detail: { key, newValue: value, oldValue, storageArea: localStorage }
}));
return result;
};
// 重写removeItem
localStorage.removeItem = function(key: string) {
const oldValue = localStorage.getItem(key);
const result = originalMethods.removeItem.call(this, key);
window.dispatchEvent(new CustomEvent('localStorageChange', {
detail: { key, newValue: null, oldValue, storageArea: localStorage }
}));
return result;
};
// 重写clear
localStorage.clear = function() {
const oldItems = { ...localStorage };
const result = originalMethods.clear.call(this);
Object.keys(oldItems).forEach(key => {
window.dispatchEvent(new CustomEvent('localStorageChange', {
detail: { key, newValue: null, oldValue: oldItems[key], storageArea: localStorage }
}));
});
return result;
};
isPatched = true;
}
现在我们需要在应用启动时调用这个补丁函数:
// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { patchLocalStorage } from './utils/localStorageMonitor';
// 在应用启动时打补丁
patchLocalStorage();
createApp(App).mount('#app');
2.3 完整Hook的集成
让我们将所有这些功能集成到一个更完善的Hook中:
// hooks/useLocalStorageEnhanced.ts
import { ref, watch, onUnmounted, onMounted } from 'vue';
import type { Ref } from 'vue';
import { patchLocalStorage } from '../utils/localStorageMonitor';
export function useLocalStorageEnhanced<T = any>(
key: string,
options: UseLocalStorageOptions<T> = {}
): {
value: Ref<T>;
setValue: (newValue: T) => void;
remove: () => void;
clearAll: () => void;
} {
const {
defaultValue,
listenToCurrentTab = true,
debounceDelay = 300,
serializer = JSON.stringify,
deserializer = JSON.parse
} = options;
// 确保localStorage已被打补丁
if (listenToCurrentTab) {
patchLocalStorage();
}
const initialValue = (() => {
try {
const stored = localStorage.getItem(key);
return stored !== null ? deserializer(stored) : defaultValue;
} catch (error) {
console.error(`Error reading localStorage key "${key}":`, error);
return defaultValue;
}
})();
const value = ref<T>(initialValue) as Ref<T>;
// 防抖相关
let debounceTimer: number | null = null;
const debounce = (fn: Function) => {
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(fn, debounceDelay);
};
// 事件处理器
const handleStorageChange = (event: StorageEvent | CustomEvent<StorageEventDetail>) => {
const isCustomEvent = 'detail' in event;
const eventKey = isCustomEvent ? event.detail.key : event.key;
const eventStorageArea = isCustomEvent ? event.detail.storageArea : event.storageArea;
if (eventKey === key && eventStorageArea === localStorage) {
debounce(() => {
try {
const newValue = isCustomEvent
? (event.detail.newValue !== null ? deserializer(event.detail.newValue) : defaultValue)
: (event.newValue !== null ? deserializer(event.newValue) : defaultValue);
value.value = newValue;
} catch (error) {
console.error(`Error processing storage change for key "${key}":`, error);
}
});
}
};
// 设置监听器
onMounted(() => {
window.addEventListener('storage', handleStorageChange as EventListener);
if (listenToCurrentTab) {
window.addEventListener('localStorageChange', handleStorageChange as EventListener);
}
});
// 清理监听器
onUnmounted(() => {
window.removeEventListener('storage', handleStorageChange as EventListener);
if (listenToCurrentTab) {
window.removeEventListener('localStorageChange', handleStorageChange as EventListener);
}
if (debounceTimer) clearTimeout(debounceTimer);
});
// 监听value变化并更新localStorage
watch(value, (newVal) => {
try {
localStorage.setItem(key, serializer(newVal));
} catch (error) {
console.error(`Error writing to localStorage key "${key}":`, error);
}
}, { deep: true });
// 操作方法
const setValue = (newValue: T) => {
value.value = newValue;
};
const remove = () => {
localStorage.removeItem(key);
value.value = defaultValue as T;
};
const clearAll = () => {
localStorage.clear();
value.value = defaultValue as T;
};
return {
value,
setValue,
remove,
clearAll
};
}
3. 高级特性与性能优化
基础功能实现后,我们需要考虑生产环境中的实际需求。大型应用往往需要更精细的控制和更好的性能表现。
3.1 批量操作与事务支持
当需要同时更新多个localStorage项时,频繁的事件触发会影响性能。我们可以实现批量更新机制:
// utils/localStorageBatch.ts
export class LocalStorageBatch {
private updates: Map<string, any> = new Map();
private static instance: LocalStorageBatch;
static getInstance(): LocalStorageBatch {
if (!LocalStorageBatch.instance) {
LocalStorageBatch.instance = new LocalStorageBatch();
}
return LocalStorageBatch.instance;
}
private constructor() {}
set(key: string, value: any): this {
this.updates.set(key, value);
return this;
}
commit(serializer: (value: any) => string = JSON.stringify): void {
const oldValues = new Map();
// 记录旧值
this.updates.forEach((value, key) => {
oldValues.set(key, localStorage.getItem(key));
});
// 批量更新
this.updates.forEach((value, key) => {
localStorage.setItem(key, serializer(value));
});
// 批量触发事件
this.updates.forEach((value, key) => {
window.dispatchEvent(new CustomEvent('localStorageChange', {
detail: {
key,
newValue: serializer(value),
oldValue: oldValues.get(key),
storageArea: localStorage
}
}));
});
this.updates.clear();
}
clear(): void {
this.updates.clear();
}
}
// 使用示例
const batch = LocalStorageBatch.getInstance();
batch
.set('theme', 'dark')
.set('language', 'zh-CN')
.set('fontSize', 14)
.commit();
3.2 内存管理与垃圾回收
长时间运行的应用可能会在localStorage中积累大量数据。我们需要实现智能的清理机制:
// utils/storageManager.ts
interface StorageItemMeta {
key: string;
timestamp: number;
size: number;
accessCount: number;
lastAccessed: number;
}
export class StorageManager {
private static readonly MAX_TOTAL_SIZE = 5 * 1024 * 1024; // 5MB
private static readonly MAX_ITEM_COUNT = 100;
private static readonly CLEANUP_THRESHOLD = 0.8; // 达到80%容量时清理
static analyzeStorage(): StorageItemMeta[] {
const items: StorageItemMeta[] = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key) {
const value = localStorage.getItem(key);
if (value) {
items.push({
key,
timestamp: Date.now(), // 实际实现中需要从值中提取时间戳
size: new Blob([value]).size,
accessCount: 0, // 需要额外的跟踪机制
lastAccessed: Date.now()
});
}
}
}
return items.sort((a, b) => a.lastAccessed - b.lastAccessed);
}
static needsCleanup(): boolean {
let totalSize = 0;
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key) {
const value = localStorage.getItem(key);
if (value) {
totalSize += new Blob([value]).size;
}
}
}
return totalSize > this.MAX_TOTAL_SIZE * this.CLEANUP_THRESHOLD ||
localStorage.length > this.MAX_ITEM_COUNT;
}
static cleanup(keepItems: string[] = []): void {
const items = this.analyzeStorage();
const itemsToRemove = items.filter(item => !keepItems.includes(item.key));
// 按LRU(最近最少使用)策略清理
itemsToRemove.forEach(item => {
localStorage.removeItem(item.key);
});
}
}
3.3 性能优化策略
为了确保监听系统不会影响应用性能,我们需要实施多种优化策略:
策略一:按需监听
不是所有组件都需要监听所有localStorage键的变化。我们可以实现选择性监听:
// hooks/useSelectiveStorage.ts
import { computed, watchEffect } from 'vue';
export function useSelectiveStorage<T = any>(
keys: string[],
options: UseLocalStorageOptions<T> = {}
) {
const { defaultValue, listenToCurrentTab = true } = options;
// 创建响应式存储对象
const storage = reactive(
keys.reduce((acc, key) => {
acc[key] = useLocalStorageEnhanced(key, options).value;
return acc;
}, {} as Record<string, Ref<T>>)
);
// 计算属性:仅当指定键变化时才重新计算
const getValues = computed(() => {
return keys.map(key => storage[key]?.value);
});
// 批量更新
const setValues = (updates: Record<string, T>) => {
Object.entries(updates).forEach(([key, value]) => {
if (keys.includes(key)) {
storage[key].value = value;
}
});
};
return {
storage,
getValues,
setValues
};
}
策略二:智能防抖 不同的应用场景需要不同的防抖策略:
// utils/debounceStrategies.ts
export interface DebounceStrategy {
delay: number;
maxWait?: number;
leading?: boolean;
trailing?: boolean;
}
export const STRATEGIES = {
// 用户交互场景:快速响应
USER_INTERACTION: {
delay: 100,
maxWait: 300,
leading: true,
trailing: false
},
// 数据同步场景:平衡性能与实时性
DATA_SYNC: {
delay: 300,
maxWait: 1000,
leading: false,
trailing: true
},
// 后台任务:优先性能
BACKGROUND: {
delay: 1000,
maxWait: 5000,
leading: false,
trailing: true
}
};
export function createDebouncedFunction(
fn: Function,
strategy: DebounceStrategy = STRATEGIES.DATA_SYNC
) {
let timeoutId: number | null = null;
let maxTimeoutId: number | null = null;
let lastCallTime: number | null = null;
return function(...args: any[]) {
const now = Date.now();
const shouldCallNow = strategy.leading && !timeoutId;
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
if (strategy.trailing) {
fn.apply(this, args);
}
timeoutId = null;
}, strategy.delay);
if (shouldCallNow) {
fn.apply(this, args);
}
if (strategy.maxWait && !maxTimeoutId) {
maxTimeoutId = setTimeout(() => {
fn.apply(this, args);
maxTimeoutId = null;
}, strategy.maxWait);
}
};
}
4. 实战应用场景与最佳实践
理论构建完成后,让我们看看在实际项目中如何应用这些技术。不同的业务场景需要不同的实现策略。
4.1 用户偏好管理系统
用户偏好是localStorage的典型应用场景。我们需要管理主题、语言、布局等多种设置:
<!-- components/UserPreferences.vue -->
<template>
<div class="preferences">
<h3>用户偏好设置</h3>
<div class="preference-item">
<label>主题模式:</label>
<select v-model="theme">
<option value="light">浅色</option>
<option value="dark">深色</option>
<option value="auto">自动</option>
</select>
</div>
<div class="preference-item">
<label>语言:</label>
<select v-model="language">
<option value="zh-CN">简体中文</option>
<option value="en-US">English</option>
<option value="ja-JP">日本語</option>
</select>
</div>
<div class="preference-item">
<label>字体大小:</label>
<input
type="range"
v-model="fontSize"
min="12"
max="24"
step="1"
>
<span>{{ fontSize }}px</span>
</div>
<div class="preference-item">
<label>动画效果:</label>
<input type="checkbox" v-model="animationsEnabled">
</div>
<button @click="resetToDefaults">恢复默认</button>
<button @click="exportPreferences">导出设置</button>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useLocalStorageEnhanced } from '../hooks/useLocalStorageEnhanced';
// 定义默认值
const DEFAULTS = {
theme: 'auto',
language: 'zh-CN',
fontSize: 16,
animationsEnabled: true
};
// 使用增强版Hook管理各个设置
const themeStorage = useLocalStorageEnhanced('user_theme', {
defaultValue: DEFAULTS.theme
});
const languageStorage = useLocalStorageEnhanced('user_language', {
defaultValue: DEFAULTS.language
});
const fontSizeStorage = useLocalStorageEnhanced('user_font_size', {
defaultValue: DEFAULTS.fontSize,
serializer: String,
deserializer: Number
});
const animationsStorage = useLocalStorageEnhanced('user_animations', {
defaultValue: DEFAULTS.animationsEnabled,
serializer: String,
deserializer: (val) => val === 'true'
});
// 计算属性提供类型安全访问
const theme = computed({
get: () => themeStorage.value,
set: (val) => themeStorage.setValue(val)
});
const language = computed({
get: () => languageStorage.value,
set: (val) => languageStorage.setValue(val)
});
const fontSize = computed({
get: () => fontSizeStorage.value,
set: (val) => fontSizeStorage.setValue(val)
});
const animationsEnabled = computed({
get: () => animationsStorage.value,
set: (val) => animationsStorage.setValue(val)
});
// 操作方法
const resetToDefaults = () => {
themeStorage.setValue(DEFAULTS.theme);
languageStorage.setValue(DEFAULTS.language);
fontSizeStorage.setValue(DEFAULTS.fontSize);
animationsStorage.setValue(DEFAULTS.animationsEnabled);
};
const exportPreferences = () => {
const preferences = {
theme: theme.value,
language: language.value,
fontSize: fontSize.value,
animationsEnabled: animationsEnabled.value,
exportedAt: new Date().toISOString()
};
const blob = new Blob([JSON.stringify(preferences, null, 2)], {
type: 'application/json'
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `preferences_${new Date().getTime()}.json`;
a.click();
URL.revokeObjectURL(url);
};
// 监听主题变化并应用到文档
import { watch } from 'vue';
watch(theme, (newTheme) => {
document.documentElement.setAttribute('data-theme', newTheme);
// 如果是自动模式,根据系统偏好设置
if (newTheme === 'auto') {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
document.documentElement.classList.toggle('dark-mode', prefersDark);
} else {
document.documentElement.classList.toggle('dark-mode', newTheme === 'dark');
}
}, { immediate: true });
// 监听字体大小变化
watch(fontSize, (newSize) => {
document.documentElement.style.fontSize = `${newSize}px`;
}, { immediate: true });
</script>
<style scoped>
.preferences {
padding: 20px;
background: var(--bg-color);
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.preference-item {
margin: 15px 0;
display: flex;
align-items: center;
gap: 10px;
}
.preference-item label {
min-width: 100px;
font-weight: 500;
}
button {
margin: 10px 5px 0 0;
padding: 8px 16px;
border: none;
border-radius: 4px;
background: var(--primary-color);
color: white;
cursor: pointer;
}
button:hover {
opacity: 0.9;
}
</style>
4.2 购物车状态同步
电商网站中,购物车状态需要在多个标签页间实时同步:
// stores/cartStore.ts
import { defineStore } from 'pinia';
import { useLocalStorageEnhanced } from '../hooks/useLocalStorageEnhanced';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
image?: string;
selected: boolean;
}
interface CartState {
items: CartItem[];
lastUpdated: number;
version: string;
}
export const useCartStore = defineStore('cart', () => {
const CART_VERSION = '1.0.0';
// 使用localStorage管理购物车状态
const cartStorage = useLocalStorageEnhanced<CartState>('shopping_cart', {
defaultValue: {
items: [],
lastUpdated: Date.now(),
version: CART_VERSION
},
debounceDelay: 500, // 购物车操作需要较长的防抖时间
listenToCurrentTab: true
});
// 计算属性
const totalItems = computed(() => {
return cartStorage.value.items.reduce((sum, item) => sum + item.quantity, 0);
});
const totalPrice = computed(() => {
return cartStorage.value.items.reduce((sum, item) => {
return sum + (item.price * item.quantity);
}, 0);
});
const selectedItems = computed(() => {
return cartStorage.value.items.filter(item => item.selected);
});
// 操作方法
const addItem = (item: Omit<CartItem, 'quantity' | 'selected'>) => {
const existingItem = cartStorage.value.items.find(i => i.id === item.id);
if (existingItem) {
existingItem.quantity += 1;
} else {
cartStorage.value.items.push({
...item,
quantity: 1,
selected: true
});
}
updateTimestamp();
};
const removeItem = (itemId: string) => {
const index = cartStorage.value.items.findIndex(item => item.id === itemId);
if (index !== -1) {
cartStorage.value.items.splice(index, 1);
updateTimestamp();
}
};
const updateQuantity = (itemId: string, quantity: number) => {
const item = cartStorage.value.items.find(i => i.id === itemId);
if (item) {
item.quantity = Math.max(1, quantity);
updateTimestamp();
}
};
const toggleSelection = (itemId: string) => {
const item = cartStorage.value.items.find(i => i.id === itemId);
if (item) {
item.selected = !item.selected;
updateTimestamp();
}
};
const clearCart = () => {
cartStorage.value.items = [];
updateTimestamp();
};
const updateTimestamp = () => {
cartStorage.value.lastUpdated = Date.now();
};
// 数据迁移(处理版本升级)
const migrateIfNeeded = () => {
if (cartStorage.value.version !== CART_VERSION) {
// 执行数据迁移逻辑
console.log(`Migrating cart from ${cartStorage.value.version} to ${CART_VERSION}`);
// 这里可以添加具体的迁移逻辑
cartStorage.value.version = CART_VERSION;
updateTimestamp();
}
};
// 初始化时检查迁移
onMounted(() => {
migrateIfNeeded();
});
return {
cart: cartStorage.value,
totalItems,
totalPrice,
selectedItems,
addItem,
removeItem,
updateQuantity,
toggleSelection,
clearCart
};
});
4.3 表单草稿自动保存
对于复杂的表单,自动保存草稿功能可以极大提升用户体验:
<!-- components/DraftForm.vue -->
<template>
<form @submit.prevent="handleSubmit" class="draft-form">
<div class="form-header">
<h2>{{ formTitle }}</h2>
<div class="draft-status" :class="draftStatusClass">
{{ draftStatusText }}
</div>
</div>
<div class="form-section">
<label>文章标题</label>
<input
v-model="formData.title"
type="text"
placeholder="请输入标题"
@input="markDirty"
>
</div>
<div class="form-section">
<label>文章内容</label>
<textarea
v-model="formData.content"
rows="10"
placeholder="请输入内容..."
@input="markDirty"
></textarea>
</div>
<div class="form-section">
<label>标签</label>
<div class="tags-input">
<input
v-model="newTag"
type="text"
placeholder="添加标签"
@keydown.enter.prevent="addTag"
>
<div class="tags-list">
<span
v-for="tag in formData.tags"
:key="tag"
class="tag"
@click="removeTag(tag)"
>
{{ tag }} ×
</span>
</div>
</div>
</div>
<div class="form-actions">
<button
type="button"
@click="restoreDraft"
:disabled="!hasDraft"
class="secondary"
>
恢复草稿
</button>
<button
type="button"
@click="clearDraft"
:disabled="!hasDraft"
class="secondary"
>
清除草稿
</button>
<button
type="submit"
:disabled="!isFormValid"
class="primary"
>
提交文章
</button>
</div>
<!-- 自动保存指示器 -->
<div v-if="isSaving" class="saving-indicator">
正在保存...
</div>
</form>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { useLocalStorageEnhanced } from '../hooks/useLocalStorageEnhanced';
interface FormData {
title: string;
content: string;
tags: string[];
lastModified: number;
}
const props = defineProps<{
formId: string;
}>();
const DRAFT_KEY = `draft_${props.formId}`;
const AUTO_SAVE_DELAY = 2000; // 2秒自动保存
const formData = ref<FormData>({
title: '',
content: '',
tags: [],
lastModified: Date.now()
});
const newTag = ref('');
const isDirty = ref(false);
const isSaving = ref(false);
const lastSaveTime = ref<number | null>(null);
// 使用localStorage管理草稿
const draftStorage = useLocalStorageEnhanced<FormData>(DRAFT_KEY, {
defaultValue: formData.value,
debounceDelay: AUTO_SAVE_DELAY,
listenToCurrentTab: true
});
// 计算属性
const hasDraft = computed(() => {
const draft = draftStorage.value;
return draft.title.trim() !== '' || draft.content.trim() !== '' || draft.tags.length > 0;
});
const draftStatusText = computed(() => {
if (isSaving.value) return '保存中...';
if (lastSaveTime.value) {
const minutesAgo = Math.floor((Date.now() - lastSaveTime.value) / 60000);
if (minutesAgo === 0) return '刚刚保存';
return `${minutesAgo}分钟前保存`;
}
return '未保存';
});
const draftStatusClass = computed(() => ({
'saving': isSaving.value,
'saved': lastSaveTime.value && !isSaving.value,
'unsaved': !lastSaveTime.value
}));
const isFormValid = computed(() => {
return formData.value.title.trim() !== '' &&
formData.value.content.trim() !== '';
});
// 标记表单为脏状态
const markDirty = () => {
isDirty.value = true;
formData.value.lastModified = Date.now();
};
// 添加标签
const addTag = () => {
const tag = newTag.value.trim();
if (tag && !formData.value.tags.includes(tag)) {
formData.value.tags.push(tag);
newTag.value = '';
markDirty();
}
};
// 移除标签
const removeTag = (tag: string) => {
const index = formData.value.tags.indexOf(tag);
if (index !== -1) {
formData.value.tags.splice(index, 1);
markDirty();
}
};
// 恢复草稿
const restoreDraft = () => {
if (confirm('恢复草稿将覆盖当前内容,是否继续?')) {
formData.value = { ...draftStorage.value };
lastSaveTime.value = Date.now();
isDirty.value = false;
}
};
// 清除草稿
const clearDraft = () => {
if (confirm('确定要清除草稿吗?此操作不可撤销。')) {
draftStorage.remove();
formData.value = {
title: '',
content: '',
tags: [],
lastModified: Date.now()
};
lastSaveTime.value = null;
isDirty.value = false;
}
};
// 处理提交
const handleSubmit = async () => {
if (!isFormValid.value) return;
try {
// 这里应该是实际的提交逻辑
console.log('提交表单数据:', formData.value);
// 提交成功后清除草稿
draftStorage.remove();
isDirty.value = false;
lastSaveTime.value = null;
alert('提交成功!');
} catch (error) {
console.error('提交失败:', error);
alert('提交失败,请重试');
}
};
// 自动保存逻辑
let saveTimeout: number | null = null;
const autoSave = () => {
if (!isDirty.value) return;
isSaving.value = true;
// 模拟网络延迟
setTimeout(() => {
draftStorage.setValue(formData.value);
isSaving.value = false;
isDirty.value = false;
lastSaveTime.value = Date.now();
}, 500);
};
// 监听表单变化,触发自动保存
watch(formData, () => {
if (isDirty.value) {
if (saveTimeout) clearTimeout(saveTimeout);
saveTimeout = setTimeout(autoSave, AUTO_SAVE_DELAY);
}
}, { deep: true });
// 页面卸载前提示
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
if (isDirty.value) {
e.preventDefault();
e.returnValue = '您有未保存的更改,确定要离开吗?';
}
};
// 初始化:检查是否有已保存的草稿
onMounted(() => {
if (hasDraft.value) {
const shouldRestore = confirm('检测到未完成的草稿,是否恢复?');
if (shouldRestore) {
restoreDraft();
}
}
window.addEventListener('beforeunload', handleBeforeUnload);
});
onUnmounted(() => {
if (saveTimeout) clearTimeout(saveTimeout);
window.removeEventListener('beforeunload', handleBeforeUnload);
// 组件卸载时自动保存
if (isDirty.value) {
autoSave();
}
});
</script>
<style scoped>
.draft-form {
max-width: 800px;
margin: 0 auto;
padding: 24px;
}
.form-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 32px;
}
.draft-status {
padding: 6px 12px;
border-radius: 16px;
font-size: 14px;
}
.draft-status.saving {
background: #fff3cd;
color: #856404;
}
.draft-status.saved {
background: #d4edda;
color: #155724;
}
.draft-status.unsaved {
background: #f8d7da;
color: #721c24;
}
.form-section {
margin-bottom: 24px;
}
.form-section label {
display: block;
margin-bottom: 8px;
font-weight: 500;
color: #333;
}
.form-section input,
.form-section textarea {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 16px;
transition: border-color 0.3s;
}
.form-section input:focus,
.form-section textarea:focus {
outline: none;
border-color: #007bff;
}
.tags-input {
border: 1px solid #ddd;
border-radius: 6px;
padding: 8px;
}
.tags-input input {
border: none;
padding: 8px;
width: 100%;
outline: none;
}
.tags-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 8px;
}
.tag {
background: #e9ecef;
padding: 4px 12px;
border-radius: 16px;
font-size: 14px;
cursor: pointer;
transition: background 0.3s;
}
.tag:hover {
background: #dc3545;
color: white;
}
.form-actions {
display: flex;
gap: 12px;
margin-top: 32px;
padding-top: 24px;
border-top: 1px solid #eee;
}
button {
padding: 12px 24px;
border: none;
border-radius: 6px;
font-size: 16px;
cursor: pointer;
transition: all 0.3s;
}
button.primary {
background: #007bff;
color: white;
}
button.primary:hover:not(:disabled) {
background: #0056b3;
}
button.secondary {
background: #6c757d;
color: white;
}
button.secondary:hover:not(:disabled) {
background: #545b62;
}
button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.saving-indicator {
position: fixed;
bottom: 20px;
right: 20px;
background: #007bff;
color: white;
padding: 12px 24px;
border-radius: 6px;
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.7; }
100% { opacity: 1; }
}
</style>
4.4 错误处理与监控
在生产环境中,完善的错误处理机制至关重要:
// utils/storageErrorHandler.ts
export class StorageError extends Error {
constructor(
message: string,
public code: string,
public key?: string,
public value?: any
) {
super(message);
this.name = 'StorageError';
}
}
export class StorageMonitor {
private errors: StorageError[] = [];
private maxErrors = 100;
logError(error: StorageError) {
this.errors.push(error);
// 保持错误队列大小
if (this.errors.length > this.maxErrors) {
this.errors.shift();
}
// 根据错误类型采取不同策略
switch (error.code) {
case 'QUOTA_EXCEEDED':
this.handleQuotaExceeded(error);
break;
case 'SECURITY_ERROR':
this.handleSecurityError(error);
break;
case 'PARSE_ERROR':
this.handleParseError(error);
break;
default:
console.error('Storage error:', error);
}
// 上报到监控系统
this.reportToMonitoring(error);
}
private handleQuotaExceeded(error: StorageError) {
console.warn('存储空间不足,尝试清理...');
// 尝试清理过期数据
this.cleanExpiredData();
// 如果仍然不足,提示用户
if (this.isQuotaStillExceeded()) {
this.showUserNotification('存储空间不足,部分功能可能受限');
}
}
private handleSecurityError(error: StorageError) {
console.warn('安全策略限制,尝试降级方案...');
// 降级到sessionStorage或内存存储
this.fallbackToAlternativeStorage();
}
private handleParseError(error: StorageError) {
console.warn('数据解析失败,尝试修复或使用默认值...');
// 尝试修复损坏的数据
const repaired = this.tryRepairData(error.key, error.value);
if (repaired) {
console.log('数据修复成功');
}
}
private cleanExpiredData() {
const now = Date.now();
const expirationTime = 7 * 24 * 60 * 60 * 1000; // 7天
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith('temp_')) {
try {
const item = JSON.parse(localStorage.getItem(key)!);
if (item.expiresAt && item.expiresAt < now) {
localStorage.removeItem(key);
}
} catch {
// 解析失败,直接删除
localStorage.removeItem(key);
}
}
}
}
private isQuotaStillExceeded(): boolean {
try {
localStorage.setItem('test_quota', 'test');
localStorage.removeItem('test_quota');
return false;
} catch {
return true;
}
}
private fallbackToAlternativeStorage() {
// 实现降级逻辑
console.log('切换到降级存储方案');
}
private tryRepairData(key?: string, value?: any): boolean {
if (!key || !value) return false;
try {
// 尝试多种修复策略
const strategies = [
this.repairByTruncation,
this.repairByEncoding,
this.repairByReconstruction
];
for (const strategy of strategies) {
if (strategy(key, value)) {
return true;
}
}
} catch {
// 修复失败
}
return false;
}
private repairByTruncation(key: string, value: any): boolean {
// 尝试截断损坏的部分
if (typeof value === 'string' && value.length > 1000) {
const repaired = value.substring(0, 1000);
localStorage.setItem(key, repaired);
return true;
}
return false;
}
private reportToMonitoring(error: StorageError) {
// 实际上报到监控系统
const metrics = {
errorCode: error.code,
errorMessage: error.message,
timestamp: Date.now(),
userAgent: navigator.userAgent,
localStorageSize: this.getLocalStorageSize()
};
// 这里可以集成Sentry、LogRocket等监控工具
if (typeof window !== 'undefined' && (window as any).Sentry) {
(window as any).Sentry.captureException(error, {
extra: metrics
});
}
}
private getLocalStorageSize(): number {
let total = 0;
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key) {
const value = localStorage.getItem(key);
if (value) {
total += key.length + value.length;
}
}
}
return total;
}
private showUserNotification(message: string) {
// 显示用户友好的通知
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
background: #ff6b6b;
color: white;
padding: 12px 24px;
border-radius: 6px;
z-index: 10000;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
document.body.removeChild(notification);
}, 5000);
}
getErrorStats() {
const stats: Record<string, number> = {};
this.errors.forEach(error => {
stats[error.code] = (stats[error.code] || 0) + 1;
});
return stats;
}
clearErrors() {
this.errors = [];
}
}
// 全局错误处理器
export const storageErrorHandler = new StorageMonitor();
// 在Hook中集成错误处理
export function useLocalStorageWithErrorHandling<T = any>(
key: string,
options: UseLocalStorageOptions<T> = {}
) {
const hook = useLocalStorageEnhanced(key, options);
// 包装原始方法,添加错误处理
const wrappedSetValue = (value: T) => {
try {
hook.setValue(value);
} catch (error) {
storageErrorHandler.logError(
new StorageError(
`Failed to set value for key "${key}"`,
'SET_ERROR',
key,
value
)
);
throw error;
}
};
return {
...hook,
setValue: wrappedSetValue
};
}
5. 测试策略与质量保障
任何生产级代码都需要完善的测试覆盖。对于localStorage监听系统,我们需要测试各种边界情况和异常场景。
5.1 单元测试
使用Vitest或Jest编写单元测试:
// tests/useLocalStorage.test.ts
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/vue';
import { useLocalStorageEnhanced } from '../hooks/useLocalStorageEnhanced';
describe('useLocalStorageEnhanced', () => {
beforeEach(() => {
// 清空localStorage
localStorage.clear();
vi.clearAllMocks();
});
afterEach(() => {
localStorage.clear();
});
it('应该使用默认值初始化', () => {
const { result } = renderHook(() =>
useLocalStorageEnhanced('test_key', { defaultValue: 'default' })
);
expect(result.value.value).toBe('default');
});
it('应该从localStorage读取已存在的值', () => {
localStorage.setItem('test_key', JSON.stringify('stored_value'));
const { result } = renderHook(() =>
useLocalStorageEnhanced('test_key', { defaultValue: 'default' })
);
expect(result.value.value).toBe('stored_value');
});
it('应该响应值的变化并更新localStorage', async () => {
const { result } = renderHook(() =>
useLocalStorageEnhanced('test_key', { defaultValue: 'initial' })
);
await act(async () => {
result.value.setValue('updated');
});
expect(result.value.value).toBe('updated');
expect(localStorage.getItem('test_key')).toBe(JSON.stringify('updated'));
});
it('应该监听storage事件(跨标签页)', async () => {
const { result } = renderHook(() =>
useLocalStorageEnhanced('test_key', { defaultValue: 'initial' })
);
// 模拟storage事件
const storageEvent = new StorageEvent('storage', {
key: 'test_key',
newValue: JSON.stringify('from_other_tab'),
oldValue: JSON.stringify('initial'),
storageArea: localStorage
});
await act(async () => {
window.dispatchEvent(storageEvent);
});
expect(result.value.value).toBe('from_other_tab');
});
it('应该处理JSON解析错误', () => {
// 设置损坏的JSON数据
localStorage.setItem('test_key', 'invalid{json');
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const { result } = renderHook(() =>
useLocalStorageEnhanced('test_key', { defaultValue: 'default' })
);
expect(result.value.value).toBe('default');
expect(consoleSpy).toHaveBeenCalled();
consoleSpy.mockRestore();
});
it('应该支持自定义序列化器', () => {
const customSerializer = (value: number) => value.toString();
const customDeserializer = (value: string) => parseInt(value, 10);
const { result } = renderHook(() =>
useLocalStorageEnhanced('test_key', {
defaultValue: 0,
serializer: customSerializer,
deserializer: customDeserializer
})
);
act(() => {
result.value.setValue(42);
});
expect(result.value.value).toBe(42);
expect(localStorage.getItem('test_key')).toBe('42');
});
it('应该正确清理事件监听器', () => {
const addEventListenerSpy = vi.spyOn(window, 'addEventListener');
const removeEventListenerSpy = vi.spyOn(window, 'removeEventListener');
const { unmount } = renderHook(() =>
useLocalStorageEnhanced('test_key', { defaultValue: 'test' })
);
unmount();
expect(removeEventListenerSpy).toHaveBeenCalledWith(
'storage',
expect.any(Function)
);
});
it('应该防抖频繁的更新', async () => {
vi.useFakeTimers();
const { result } = renderHook(() =>
useLocalStorageEnhanced('test_key', {
defaultValue: 'initial',
debounceDelay: 100
})
);
const setItemSpy = vi.spyOn(localStorage, 'setItem');
// 快速连续设置多次
act(() => {
result.value.setValue('update1');
result.value.setValue('update2');
result.value.setValue('update3');
});
// localStorage应该还没有被更新
expect(setItemSpy).not.toHaveBeenCalled();
// 快进时间
await act(async () => {
vi.advanceTimersByTime(100);
});
// 现在应该只更新了一次
expect(setItemSpy).toHaveBeenCalledTimes(1);
expect(localStorage.getItem('test_key')).toBe(JSON.stringify('update3'));
vi.useRealTimers();
});
});
5.2 集成测试
测试与其他Vue3特性的集成:
// tests/integration/withPinia.test.ts
import { describe, it, expect, beforeEach } from 'vitest';
import { createPinia, setActivePinia } from 'pinia';
import { mount } from '@vue/test-utils';
import { useLocalStorageEnhanced } from '../../hooks/useLocalStorageEnhanced';
describe('与Pinia集成', () => {
beforeEach(() => {
setActivePinia(createPinia());
localStorage.clear();
});
it('应该在Pinia store中正常工作', () => {
const useTestStore = defineStore('test', () => {
const count = useLocalStorageEnhanced('count', { defaultValue: 0 });
const increment = () => {
count.value += 1;
};
return { count, increment };
});
const store = useTestStore();
expect(store.count.value).toBe(0);
store.increment();
expect(store.count.value).toBe(1);
expect(localStorage.getItem('count')).toBe('1');
});
it('应该在不同组件间共享状态', async () => {
const ComponentA = defineComponent({
setup() {
const count = useLocalStorageEnhanced('shared_count', { defaultValue: 0 });
const increment = () => count.value += 1;
return { count, increment };
},
template: '<button @click="increment">A: {{ count }}</button>'
});
const ComponentB = defineComponent({
setup() {
const count = useLocalStorageEnhanced('shared_count', { defaultValue: 0 });
return { count };
},
template: '<div>B: {{ count }}</div>'
});
const wrapperA = mount(ComponentA);
const wrapperB = mount(ComponentB);
expect(wrapperA.text()).toContain('A: 0');
expect(wrapperB.text()).toContain('B: 0');
await wrapperA.find('button').trigger('click');
expect(wrapperA.text()).toContain('A: 1');
expect(wrapperB.text()).toContain('B: 1');
});
});
5.3 性能测试
确保监听系统不会影响应用性能:
// tests/performance/storagePerformance.test.ts
import { describe, it, expect, vi } from 'vitest';
import { useLocalStorageEnhanced } from '../../hooks/useLocalStorageEnhanced';
describe('性能测试', () => {
it('大量数据操作时的性能', () => {
const ITEM_COUNT = 1000;
const startTime = performance.now();
// 创建大量存储项
const hooks = Array.from({ length: ITEM_COUNT }, (_, i) => {
return useLocalStorageEnhanced(`item_${i}`, { defaultValue: i });
});
// 批量更新
hooks.forEach((hook, i) => {
hook.setValue(i * 2);
});
const endTime = performance.now();
const duration = endTime - startTime;
console.log(`处理${ITEM_COUNT}个项耗时: ${duration}ms`);
// 性能断言:处理1000个项应该在500ms内
expect(duration).toBeLessThan(500);
});
it('频繁更新时的防抖效果', async () => {
vi.useFakeTimers();
const { result } = renderHook(() =>
useLocalStorageEnhanced('perf_test', {
defaultValue: 0,
debounceDelay: 50
})
);
const setItemSpy = vi.spyOn(localStorage, 'setItem');
const startTime = performance.now();
// 模拟快速连续更新
for (let i = 0; i < 100; i++) {
result.value.setValue(i);
}
// 快进时间
await act(async () => {
vi.advanceTimersByTime(50);
});
const endTime = performance.now();
const duration = endTime - startTime;
// 应该只触发了一次实际的存储操作
expect(setItemSpy).toHaveBeenCalledTimes(1);
console.log(`防抖处理100次更新耗时: ${duration}ms`);
vi.useRealTimers();
});
it('内存使用情况', () => {
const initialMemory = (performance as any).memory?.usedJSHeapSize || 0;
// 创建多个Hook实例
const hooks = [];
for (let i = 0; i < 100; i++) {
hooks.push(useLocalStorageEnhanced(`mem_test_${i}`, { defaultValue: {} }));
}
const finalMemory = (performance as any).memory?.usedJSHeapSize || 0;
const memoryIncrease = finalMemory - initialMemory;
console.log(`内存增加: ${(memoryIncrease / 1024).toFixed(2)}KB`);
// 内存增加应该在合理范围内
expect(memoryIncrease).toBeLessThan(10 * 1024 * 1024); // 小于10MB
});
});
6. 部署与维护建议
将这套系统部署到生产环境时,需要考虑一些额外的因素。
6.1 版本管理与数据迁移
随着应用迭代,存储结构可能发生变化:
// utils/storageMigration.ts
interface Migration {
version: string;
description: string;
migrate: (data: any) => any;
}
export class StorageMigrationManager {
private static readonly MIGRATION_KEY = '_storage_migrations';
private static migrations: Migration[] = [];
static registerMigration(migration: Migration) {
this.migrations.push(migration);
this.migrations.sort((a, b) => this.compareVersions(a.version, b.version));
}
static async runMigrations() {
const appliedMigrations = this.getAppliedMigrations();
const pendingMigrations = this.migrations.filter(
m => !appliedMigrations.includes(m.version)
);
for (const migration of pendingMigrations) {
try {
console.log(`Applying migration: ${migration.version} - ${migration.description}`);
// 执行迁移
await this.applyMigration(migration);
// 记录已应用的迁移
this.recordAppliedMigration(migration.version);
console.log(`Migration ${migration.version} completed successfully`);
} catch (error) {
console.error(`Migration ${migration.version} failed:`, error);
throw error;
}
}
}
private static async applyMigration(migration: Migration) {
// 迁移所有相关数据
const keysToMigrate = this.findKeysToMigrate();
for (const key of keysToMigrate) {
try {
const value = localStorage.getItem(key);
if (value) {
const parsed = JSON.parse(value);
const migrated = migration.migrate(parsed);
localStorage.setItem(key, JSON.stringify(migrated));
}
} catch (error) {
console.warn(`Failed to migrate key ${key}:`, error);
}
}
}
private static findKeysToMigrate(): string[] {
const keys: string[] = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && !key.startsWith('_')) { // 跳过系统键
keys.push(key);
}
}
return keys;
}
private static getAppliedMigrations(): string[] {
const applied = localStorage.getItem(this.MIGRATION_KEY);
return applied ? JSON.parse(applied) : [];
}
private static recordAppliedMigration(version: string) {
const applied = this.getAppliedMigrations();
if (!applied.includes(version)) {
applied.push(version);
localStorage.setItem(this.MIGRATION_KEY, JSON.stringify(applied));
}
}
private static compareVersions(a: string, b: string): number {
const partsA = a.split('.').map(Number);
const partsB = b.split('.').map(Number);
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const partA = partsA[i] || 0;
const partB = partsB[i] || 0;
if (partA !== partB) {
return partA - partB;
}
}
return 0;
}
}
// 注册示例迁移
StorageMigrationManager.registerMigration({
version: '1.1.0',
description: '将用户设置从扁平结构改为嵌套结构',
migrate: (data) => {
if (data && typeof data === 'object') {
// 旧格式: { theme: 'dark', language: 'zh-CN' }
// 新格式: { preferences: { theme: 'dark', language: 'zh-CN' } }
if (data.theme || data.language) {
return {
preferences: {
theme: data.theme || 'auto',
language: data.language || 'zh-CN',
migratedAt: new Date().toISOString()
}
};
}
}
return data;
}
});
StorageMigrationManager.registerMigration({
version: '1.2.0',
description: '为购物车项添加唯一标识符',
migrate: (data) => {
if (data && Array.isArray(data.items)) {
return {
...data,
items: data.items.map((item: any, index: number) => ({
...item,
uuid: item.uuid || `item_${Date.now()}_${index}`
}))
};
}
return data;
}
});
6.2 监控与告警
在生产环境中监控存储系统的健康状态:
// utils/storageMonitor.ts
export class ProductionStorageMonitor {
private static readonly METRICS_KEY = '_storage_metrics';
private static instance: ProductionStorageMonitor;
static getInstance(): ProductionStorageMonitor {
if (!ProductionStorageMonitor.instance) {
ProductionStorageMonitor.instance = new ProductionStorageMonitor();
}
return ProductionStorageMonitor.instance;
}
private metrics = {
totalOperations: 0,
failedOperations: 0,
quotaUsage: 0,
lastCleanup: 0,
errorTypes: {} as Record<string, number>
};
private constructor() {
this.loadMetrics();
this.startReporting();
}
recordOperation(success: boolean, operation: string, key?: string) {
this.metrics.totalOperations++;
if (!success) {
this.metrics.failedOperations++;
this.metrics.errorTypes[operation] = (this.metrics.errorTypes[operation] || 0) + 1;
}
this.updateQuotaUsage();
this.saveMetrics();
// 触发告警检查
this.checkAlerts();
}
private updateQuotaUsage() {
let totalSize = 0;
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key) {
const value = localStorage.getItem(key);
if (value) {
totalSize += new Blob([key + value]).size;
}
}
}
// 假设最大配额为5MB
const maxQuota = 5 * 1024 * 1024;
this.metrics.quotaUsage = (totalSize / maxQuota) * 100;
}
private checkAlerts() {
// 错误率告警
const errorRate = this.metrics.failedOperations / Math.max(this.metrics.totalOperations, 1);
if (errorRate > 0.1) { // 错误率超过10%
this.triggerAlert('HIGH_ERROR_RATE', `存储操作错误率过高: ${(errorRate * 100).toFixed(1)}%`);
}
// 配额告警
if (this.metrics.quotaUsage > 80) {
this.triggerAlert('HIGH_QUOTA_USAGE', `存储使用率过高: ${this.metrics.quotaUsage.toFixed(1)}%`);
}
// 需要清理
if (this.metrics.quotaUsage > 90) {
this.performCleanup();
}
}
private performCleanup() {
const now = Date.now();
const oneWeekAgo = now - 7 * 24 * 60 * 60 * 1000;
let cleanedCount = 0;
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith('temp_')) {
try {
const item = JSON.parse(localStorage.getItem(key)!);
if (item.createdAt && item.createdAt < oneWeekAgo) {
localStorage.removeItem(key);
cleanedCount++;
}
} catch {
localStorage.removeItem(key);
cleanedCount++;
}
}
}
this.metrics.lastCleanup = now;
console.log(`清理了 ${cleanedCount} 个过期项目`);
}
private triggerAlert(type: string, message: string) {
// 集成到现有的告警系统
console.warn(`[Storage Alert] ${type}: ${message}`);
// 这里可以集成到Sentry、Datadog等
if (typeof window !== 'undefined' && (window as any).Sentry) {
(window as any).Sentry.captureMessage(message, {
level: 'warning',
tags: { alert_type: type }
});
}
}
private startReporting() {
// 每分钟上报一次指标
setInterval(() => {
this.reportMetrics();
}, 60 * 1000);
}
private reportMetrics() {
const report = {
timestamp: Date.now(),
metrics: this.metrics,
userAgent: navigator.userAgent,
localStorageKeys: this.getKeyStats()
};
// 实际上报到监控后端
this.sendToBackend(report);
}
private getKeyStats() {
const stats = {
total: localStorage.length,
byPrefix: {} as Record<string, number>,
totalSize: 0
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key) {
const value = localStorage.getItem(key);
// 按前缀统计
const prefix = key.split('_')[0];
stats.byPrefix[prefix] = (stats.byPrefix[prefix] || 0) + 1;
// 计算总大小
if (value) {
stats.totalSize += new Blob([key + value]).size;
}
}
}
return stats;
}
private sendToBackend(data: any) {
// 使用navigator.sendBeacon或fetch上报
const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
if (navigator.sendBeacon) {
navigator.sendBeacon('/api/storage-metrics', blob);
} else {
fetch('/api/storage-metrics', {
method: 'POST',
body: blob,
keepalive: true
});
}
}
private loadMetrics() {
try {
const saved = localStorage.getItem(this.METRICS_KEY);
if (saved) {
this.metrics = JSON.parse(saved);
}
} catch {
// 忽略解析错误
}
}
private saveMetrics() {
try {
localStorage.setItem(this.METRICS_KEY, JSON.stringify(this.metrics));
} catch {
// 忽略存储错误
}
}
getMetrics() {
return { ...this.metrics };
}
}
// 在Hook中集成监控
export function useMonitoredLocalStorage<T = any>(
key: string,
options: UseLocalStorageOptions<T> = {}
) {
const monitor = ProductionStorageMonitor.getInstance();
const hook = useLocalStorageEnhanced(key, options);
// 包装方法以记录指标
const monitoredSetValue = (value: T) => {
try {
hook.setValue(value);
monitor.recordOperation(true, 'set', key);
} catch (error) {
monitor.recordOperation(false, 'set', key);
throw error;
}
};
return {
...hook,
setValue: monitoredSetValue
};
}
6.3 浏览器兼容性处理
虽然现代浏览器都支持localStorage,但仍需处理一些边缘情况:
// utils/compatibility.ts
export class StorageCompatibility {
static isLocalStorageSupported(): boolean {
try {
const testKey = '__test__';
localStorage.setItem(testKey, testKey);
localStorage.removeItem(testKey);
return true;
} catch {
return false;
}
}
static getStorageFallback(): Storage {
if (this.isLocalStorageSupported()) {
return localStorage;
}
// 降级方案:使用内存存储
return this.createMemoryStorage();
}
private static createMemoryStorage(): Storage {
let data: Record<string, string> = {};
return {
get length() {
return Object.keys(data).length;
},
key(index: number): string | null {
return Object.keys(data)[index] || null;
},
getItem(key: string): string | null {
return data[key] || null;
},
setItem(key: string, value: string): void {
data[key] = value;
// 模拟storage事件
window.dispatchEvent(new StorageEvent('storage', {
key,
newValue: value,
oldValue: data[key],
storageArea: this
}));
},
removeItem(key: string): void {
const oldValue = data[key];
delete data[key];
window.dispatchEvent(new StorageEvent('storage', {
key,
newValue: null,
oldValue,
storageArea: this
}));
},
clear(): void {
const oldData = { ...data };
data = {};
Object.keys(oldData).forEach(key => {
window.dispatchEvent(new StorageEvent('storage', {
key,
newValue: null,
oldValue: oldData[key],
storageArea: this
}));
});
}
} as Storage;
}
static handlePrivateBrowsing(): Storage {
// 处理Safari隐私浏览模式等特殊情况
try {
localStorage.setItem('test', 'test');
localStorage.removeItem('test');
return localStorage;
} catch (error) {
console.warn('Private browsing detected, using memory storage');
return this.createMemoryStorage();
}
}
static getQuotaInfo(): {
supported: boolean;
estimatedQuota?: number;
usage?: number;
} {
if ('storage' in navigator && 'estimate' in navigator.storage) {
return {
supported: true,
estimatedQuota: undefined,
usage: undefined
};
}
return { supported: false };
}
}
// 兼容性增强的Hook
export function useCompatibleLocalStorage<T = any>(
key: string,
options: UseLocalStorageOptions<T> = {}
) {
const storage = StorageCompatibility.getStorageFallback
5109



被折叠的 条评论
为什么被折叠?



