在 Vue 3 中實現本地存儲(如用戶配置數據),主要通過瀏覽器提供的?localStorage
?或?sessionStorage
?API。以下是詳細實現方案:
基礎實現(原生 API)
javascript
復制
下載
// 存儲數據 localStorage.setItem('userSettings', JSON.stringify({ theme: 'dark', fontSize: 16 }));// 讀取數據 const settings = JSON.parse(localStorage.getItem('userSettings')) || {};// 刪除數據 localStorage.removeItem('userSettings');
推薦方案:封裝響應式存儲工具
在?/src/composables/useLocalStorage.js
?中創建可復用邏輯:
javascript
復制
下載
import { ref, watchEffect } from 'vue';export default function useLocalStorage(key, defaultValue) {// 創建響應式引用const storedValue = ref(JSON.parse(localStorage.getItem(key)) || defaultValue);// 監聽變化并存儲watchEffect(() => {localStorage.setItem(key, JSON.stringify(storedValue.value));});// 提供清除方法const clearStorage = () => {localStorage.removeItem(key);storedValue.value = defaultValue;};return [storedValue, clearStorage]; }
在組件中使用
vue
復制
下載
<script setup> import { computed } from 'vue'; import useLocalStorage from '@/composables/useLocalStorage';// 使用存儲鉤子(帶默認值) const [userSettings, clearSettings] = useLocalStorage('userConfig', {theme: 'light',fontSize: 14,notifications: true });// 修改配置 const toggleTheme = () => {userSettings.value.theme = userSettings.value.theme === 'light' ? 'dark' : 'light'; };// 計算屬性示例 const themeClass = computed(() => `theme-${userSettings.value.theme}`); </script><template><div :class="themeClass"><button @click="toggleTheme">切換主題</button><button @click="clearSettings">重置配置</button><input type="range" min="12" max="24"v-model.number="userSettings.fontSize"></div> </template>
高級技巧
-
存儲加密(敏感數據):
javascript
復制
下載
import CryptoJS from 'crypto-js';const SECRET_KEY = import.meta.env.VITE_STORAGE_SECRET;// 加密存儲 const encryptedData = CryptoJS.AES.encrypt(JSON.stringify(data),SECRET_KEY ).toString();// 解密讀取 const bytes = CryptoJS.AES.decrypt(storedData, SECRET_KEY); const originalData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
-
類型安全存取:
javascript
復制
下載
// 增強版存儲方法 const typedStorage = {get(key, type = 'string') {const value = localStorage.getItem(key);if (value === null) return null;try {return {'number': Number(value),'boolean': value === 'true','object': JSON.parse(value),'array': JSON.parse(value)}[type] || value;} catch {return value;}},set(key, value) {const type = typeof value;const toStore = ['object', 'array'].includes(type) ? JSON.stringify(value) : value;localStorage.setItem(key, toStore);} };
注意事項
-
存儲限制:
-
單個域名存儲上限通常為 5MB
-
單個鍵值對建議不超過 2MB
-
-
最佳實踐:
javascript
復制
下載
// 1. 添加存儲版本控制 const STORAGE_VERSION = 'v1'; const storageKey = `${STORAGE_VERSION}_userConfig`;// 2. 添加存儲錯誤處理 try {localStorage.setItem(key, data); } catch (e) {console.error('存儲失敗:', e);// 降級方案:使用 sessionStorage 或內存存儲 }// 3. 監聽跨標簽頁更新 window.addEventListener('storage', (event) => {if (event.key === storageKey) {// 更新本地數據userSettings.value = JSON.parse(event.newValue);} });
-
替代方案選擇:
方案 特點 適用場景 localStorage 永久存儲 用戶配置、長期數據 sessionStorage 標簽頁關閉即清除 臨時表單數據 IndexedDB 大容量存儲 (250MB+) 離線應用、大型數據 Cookies 自動攜帶到請求頭 身份認證
完整示例(TypeScript 版)
typescript
復制
下載
// useLocalStorage.ts import { ref, watch, Ref } from 'vue';type StorageValue<T> = Ref<T>;export default function useLocalStorage<T>(key: string, defaultValue: T ): [StorageValue<T>, () => void] {const storedValue = ref(defaultValue) as StorageValue<T>;// 初始化讀取try {const item = localStorage.getItem(key);if (item !== null) {storedValue.value = JSON.parse(item);}} catch (error) {console.error(`讀取 ${key} 失敗:`, error);}// 監聽變化watch(storedValue, (newVal) => {try {localStorage.setItem(key, JSON.stringify(newVal));} catch (error) {console.error(`存儲 ${key} 失敗:`, error);}}, { deep: true });const clear = () => {localStorage.removeItem(key);storedValue.value = defaultValue;};return [storedValue, clear]; }
通過這種方式,您可以:
-
創建響應式的持久化存儲
-
自動同步 localStorage 變化
-
支持復雜對象存儲
-
提供類型安全(TypeScript)
-
處理存儲異常情況