浏览器中常见的过期存储方式为 Cookie 。Cookie 可以设置存储内容的过期时间、立即过期等等,但是 Cookie 的大小限制为 4KB(4096字节)。这是指整个 Cookie(包括名称、值、过期时间、路径、域等信息)的总大小不能超过 4KB。如果你使用的是 Cookie 登录的方式,那么 Cookie 中的内容将自动携带进后端需要 Cookie 的请求头中,这非常不友好,于是,我设计了如下这种方式的自动过期方案的 localStorage 持久化
tsexport function getExpiredStorage(storage: Storage, expiresTime: string | number | Date) {
return {
getItem(key: string) {
// pinia 的持久化插件要求返回字符串
return JSON.stringify(storage.get(key))
},
setItem(key: string, value: string) {
console.log('storage.set(key, value)', key, value)
storage.set(key, value, expiresTime)
},
removeItem(key: string) {
storage.remove(key)
},
clear() {
storage.keys().forEach((key: any) => {
storage.remove(key)
})
},
key(index: number): string | null {
return storage.keys()[index] || null
},
length: storage.keys().length,
} as Storage
}
const { cookies } = useCookies()
const expiresTime = 60 * 30 // 自定义过期时间 30 分钟
const expiredStorage = getExpiredStorage(cookies, expiresTime)
export const useUserStore = defineStore(
'userStore',
() => {
// 略
},
{
persist: {
storage: expiredStorage,
debug: true,
},
},
)
tsexport function getExpiredStorage(storage: Storage, expiresTime: string | number | Date) {
return {
getItem(key: string) {
const itemStr = storage.getItem(key)
if (!itemStr) {
return null
}
// 读取的时候是字符串,需要转换为对象
const item = JSON.parse(itemStr)
const now = new Date()
if (now.getTime() > item.expiry) {
storage.removeItem(key)
return null
}
// pinia 的持久化插件要求返回JSON字符串
return JSON.stringify(item.value)
},
setItem(key: string, value: string) {
const now = new Date()
const item = {
value: JSON.parse(value), // value是JSON字符串,需要转换为对象
expiry: now.getTime() + Number(expiresTime) * 1000,
}
storage.setItem(key, JSON.stringify(item)) // 存储又要转为JSON字符串
},
removeItem(key: string) {
storage.removeItem(key)
},
clear() {
Object.keys(storage).forEach((key: string) => {
storage.removeItem(key)
})
},
key(index: number): string | null {
const keys = Object.keys(storage)
return keys[index] || null
},
length: Object.keys(storage).length,
} as Storage
}
const expiresTime = 60 * 30 // 自定义过期时间 30 分钟
const expiredStorage = getExpiredStorage(localStorage, expiresTime)
export const useUserStore = defineStore(
'userStore',
() => {
// 略
},
{
persist: {
storage: expiredStorage,
debug: true,
},
},
)
这个数据在30分钟后再次读取将自动清除
本文作者:peepdd864
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!