目錄
一、基本用法(原生 API)
1. 存儲數據
2. 獲取數據
3. 刪除數據
二、Vue3 中封裝成工具函數(推薦)
三、以上工具函數在 Vue3 組件中使用
1. 在選項式 API 中使用
2. 在組合式 API(setup 語法糖)中使用
四、將存儲結合 Pinia 實現響應式存儲(高級用法)
1. 在組件中使用
五、注意事項
一、基本用法(原生 API)
本地存儲和會話存儲的核心 API 完全一致,區別在于:
- localStorage:數據持久化存儲,關閉瀏覽器后不會丟失(除非手動清除)
- sessionStorage:數據僅在當前會話有效,關閉標簽頁 / 瀏覽器后自動清除
1. 存儲數據
// 存儲到本地存儲
localStorage.setItem('userName', '張三'); // 存儲字符串
localStorage.setItem('userInfo', JSON.stringify({ id: 1, name: '張三' })); // 存儲對象(需序列化)// 存儲到會話存儲
sessionStorage.setItem('token', 'abc123');
sessionStorage.setItem('cart', JSON.stringify([{ id: 1, name: '商品' }]));
2. 獲取數據
// 從本地存儲獲取
const userName = localStorage.getItem('userName'); // 獲取字符串
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}'); // 獲取對象(需反序列化)// 從會話存儲獲取
const token = sessionStorage.getItem('token');
const cart = JSON.parse(sessionStorage.getItem('cart') || '[]');
3. 刪除數據
// 刪除單個數據
localStorage.removeItem('userName');
sessionStorage.removeItem('token');// 清空所有數據
localStorage.clear(); //清空本地存儲
sessionStorage.clear(); //清空會話存儲
二、Vue3 中封裝成工具函數(推薦)
為了更方便使用,可以將以上這些方法封裝成工具函數,放在?utils/storage.js
?中,封裝如下:
// 本地存儲工具函數
export const LocalStorage = {// 設置數據set(key, value) {if (typeof value === 'object') {value = JSON.stringify(value);}localStorage.setItem(key, value);},// 獲取數據get(key) {const value = localStorage.getItem(key);if (!value) return null;// 嘗試解析為對象try {return JSON.parse(value);} catch (e) {return value; // 解析失敗則返回原始字符串}},// 刪除數據remove(key) {localStorage.removeItem(key);},// 清空所有數據clear() {localStorage.clear();}
};// 會話存儲工具函數
export const SessionStorage = {set(key, value) {if (typeof value === 'object') {value = JSON.stringify(value);}sessionStorage.setItem(key, value);},get(key) {const value = sessionStorage.getItem(key);if (!value) return null;try {return JSON.parse(value);} catch (e) {return value;}},remove(key) {sessionStorage.removeItem(key);},clear() {sessionStorage.clear();}
};
三、以上工具函數在 Vue3 組件中使用
1. 在選項式 API 中使用
<template><div><p>用戶名:{{ userName }}</p><button @click="saveUser">保存用戶信息</button></div>
</template><script>
import { LocalStorage } from '@/utils/storage';export default {data() {return {userName: ''};},mounted() {// 組件掛載時獲取本地存儲的數據this.userName = LocalStorage.get('userName') || '未登錄';},methods: {saveUser() {// 保存數據到本地存儲LocalStorage.set('userName', '張三');LocalStorage.set('userInfo', { id: 1, age: 20 });this.userName = '張三';}}
};
</script>
2. 在組合式 API(setup 語法糖)中使用
<template><div><p>Token:{{ token }}</p><button @click="saveToken">保存Token</button></div>
</template><script setup>
import { ref, onMounted } from 'vue';
import { SessionStorage } from '@/utils/storage';// 響應式變量
const token = ref('');// 組件掛載時獲取會話存儲的數據
onMounted(() => {token.value = SessionStorage.get('token') || '無';
});// 保存數據到會話存儲
const saveToken = () => {SessionStorage.set('token', 'abc123456');token.value = 'abc123456';
};
</script>
四、將存儲結合 Pinia 實現響應式存儲(高級用法)
如果需要讓存儲的數據在組件中保持響應式(數據變化時自動更新視圖),可以結合 Pinia 狀態管理,如下:
import { defineStore } from 'pinia';
import { LocalStorage } from '@/utils/storage';export const useStorageStore = defineStore('storage', {state: () => ({// 從本地存儲初始化數據(響應式)userInfo: LocalStorage.get('userInfo') || {},theme: LocalStorage.get('theme') || 'light'}),actions: {// 更新用戶信息并同步到本地存儲setUserInfo(info) {this.userInfo = info;LocalStorage.set('userInfo', info); // 同步到本地存儲},// 更新主題并同步到本地存儲setTheme(theme) {this.theme = theme;LocalStorage.set('theme', theme);}}
});
1. 在組件中使用
<template><div><p>用戶名稱:{{ storageStore.userInfo.name }}</p><button @click="updateUser">更新用戶信息</button></div>
</template><script setup>
import { useStorageStore } from '@/stores/storage';const storageStore = useStorageStore();const updateUser = () => {storageStore.setUserInfo({ id: 1, name: '李四', age: 25 });
};
</script>
五、注意事項
- 存儲容量限制:localStorage 和 sessionStorage 通常有 5MB 左右的容量限制,不適合存儲大量數據
- 數據類型限制:只能存儲字符串,對象 / 數組需要通過?
JSON.stringify()
?序列化- 安全性:存儲在本地的信息容易被篡改,敏感數據(如密碼)不應直接存儲
- 跨域限制:不同域名之間不能共享 localStorage/sessionStorage 數據
- 響應式問題:直接修改 localStorage 不會觸發 Vue 組件更新,需手動刷新或結合 Pinia 實現響應式
根據需求選擇合適的存儲方式:需要持久化的數據用 localStorage,臨時會話數據用 sessionStorage。