🔥 2025年8月快讯:最新Chrome 118版本优化了localStorage的存取性能,在SSD设备上读写速度提升约15%!同时Safari 21正式支持了localStorage的"配额查询API",开发者现在可以更精确管理存储空间了~
localStorage是浏览器提供的一种本地存储方案,相比cookie,它有这些优势:
// 基本操作就像操作对象一样简单 localStorage.setItem('key', 'value') // 存 const data = localStorage.getItem('key') // 取 localStorage.removeItem('key') // 删
export default { methods: { saveUser() { localStorage.setItem('user', JSON.stringify({ name: '小明', age: 25 })) }, loadUser() { const user = JSON.parse(localStorage.getItem('user') || '{}') console.log(user.name) // 小明 } } }
⚠️ 注意:localStorage只能存字符串,对象要用JSON.stringify
转换!
创建storage.js
:
const StoragePlugin = { install(app) { app.config.globalProperties.$storage = { set(key, value) { localStorage.setItem(key, JSON.stringify(value)) }, get(key) { return JSON.parse(localStorage.getItem(key)) }, remove(key) { localStorage.removeItem(key) } } } } export default StoragePlugin
在main.js中使用:
import StoragePlugin from './storage' app.use(StoragePlugin)
组件内调用:
this.$storage.set('theme', 'dark') // 爽!
// stores/userStore.js import { defineStore } from 'pinia' export const useUserStore = defineStore('user', { state: () => ({ token: JSON.parse(localStorage.getItem('token')) || null }), actions: { setToken(token) { this.token = token localStorage.setItem('token', JSON.stringify(token)) }, clearToken() { this.token = null localStorage.removeItem('token') } } })
容量检测(新特性!)
if (navigator.storage) { const { usage, quota } = await navigator.storage.estimate() console.log(`已用${usage}字节,剩余${quota - usage}字节`) }
自动过期设置
function setWithExpiry(key, value, expiryDays) { const item = { value, expiry: Date.now() + expiryDays * 86400000 } localStorage.setItem(key, JSON.stringify(item)) }
function getWithExpiry(key) { const itemStr = localStorage.getItem(key) if (!itemStr) return null
const item = JSON.parse(itemStr) if (Date.now() > item.expiry) { localStorage.removeItem(key) return null } return item.value }
3. **TypeScript支持**(2025标配)
```typescript
interface UserData {
id: number
name: string
lastLogin: string
}
const setUser = (user: UserData) => {
localStorage.setItem('user', JSON.stringify(user))
}
const getUser = (): UserData | null => {
const data = localStorage.getItem('user')
return data ? JSON.parse(data) : null
}
隐私模式报错:Safari隐身模式下localStorage会报QuotaExceededError
try { localStorage.setItem('test', 'test') } catch (e) { console.warn('隐私模式不可用,自动降级到内存存储') }
Vue3响应式问题:直接修改localStorage不会触发组件更新
// ❌ 不会触发更新 localStorage.setItem('count', 10)
// ✅ 正确做法(组合式API示例) import { ref, watchEffect } from 'vue'
const count = ref(JSON.parse(localStorage.getItem('count')) || 0)
watchEffect(() => { localStorage.setItem('count', JSON.stringify(count.value)) })
3. **XSS风险**:不要存储敏感信息!黑客可以通过控制台直接查看localStorage
## 五、替代方案比较 🆚
| 特性 | localStorage | sessionStorage | Cookie | IndexedDB |
|---------------|-------------|----------------|-------------|-------------|
| 容量 | 5MB | 5MB | 4KB | 无限制 |
| 生命周期 | 永久 | 会话级 | 可设置 | 永久 |
| 服务端是否可用| ❌ | ❌ | ✅ | ❌ |
| 2025推荐场景 | 用户偏好设置 | 表单草稿 | 认证token | 大型离线应用 |
## 六、实战案例:实现主题切换 🌓
```vue
<script setup>
import { ref, watch } from 'vue'
const themes = ['light', 'dark', 'blue']
const currentTheme = ref(
JSON.parse(localStorage.getItem('theme')) || 'light'
)
watch(currentTheme, (newVal) => {
document.documentElement.setAttribute('data-theme', newVal)
localStorage.setItem('theme', JSON.stringify(newVal))
}, { immediate: true })
</script>
<template>
<select v-model="currentTheme">
<option v-for="theme in themes" :key="theme" :value="theme">
{{ theme }}主题
</option>
</select>
</template>
根据2025年Web存储标准草案,可能会有这些变化:
💡 小贴士:在Vite项目中,可以使用vite-plugin-persist
实现更强大的持久化存储,支持自动类型推断和加密功能哦!
现在就去试试这些技巧吧,让你的Vue应用拥有更专业的本地存储方案! 🎉
本文由 吕雨竹 于2025-08-02发表在【云服务器提供商】,文中图片由(吕雨竹)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/517788.html
发表评论