我定义了一个 Cache 类,它可以通过构造函数选择使用 localStorage 或 sessionStorage 存储缓存数据。setCache 方法可以将一个 key-value 对存储到缓存中,getCache 方法可以根据给定的 key 获取对应的 value,removeCache 方法可以删除一个缓存项,clear 方法可以清空存储的所有缓存数据。
通过 localCache 和 sessionCache 这两个实例,我们可以创建 localStorage 和 sessionStorage 的缓存实例,并通过它们来存储和获取数据。这种设计可以使我们在不同的存储场景下使用相同的 API,降低开发难度,并且很容易进行扩展,比如可以增加一个 RedisCache 类来支持使用 Redis 进行缓存
enum CacheType {
Local,
Session
}
class Cache {
storage: Storage
constructor(type: CacheType) {
this.storage = type === CacheType.Local ? localStorage : sessionStorage
}
setCache(key: string, value: any) {
if (value) {
this.storage.setItem(key, JSON.stringify(value))
}
}
getCache(key: string) {
const value = this.storage.getItem(key)
if (value) {
return JSON.parse(value)
}
}
removeCache(key: string) {
this.storage.removeItem(key)
}
clear() {
this.storage.clear()
}
}
const localCache = new Cache(CacheType.Local)
const sessionCache = new Cache(CacheType.Session)
export { localCache, sessionCache }
这里 store 用于管理登录相关的状态和行为。
在 state 中,定义了三个状态属性:id、token 和 name。id 初始值为空字符串,token 的初始值是通过调用 localCache.getCache('token') 来获取的本地缓存值,如果不存在缓存值,则取空字符串。name 初始化为一个空字符串。
在 actions 中,定义了一个异步的 loginAccountAction 方法,用于处理账号登录的逻辑。在这个方法中,首先调用了 accountLoginRequest 方法来进行账号登录并获取登录结果,然后通过 loginResult.data 来获取返回的登录信息,包括 id、token 和 name。接着,将这些信息分别赋值给 store 中的对应状态属性。
最后,通过调用 localCache.setCache('token', this.token) 将登录成功后的 token 保存到本地缓存中,以便在页面刷新后仍然可以获取到登录状态。
总的来说,这段代码实现了登录的逻辑,通过 Vuex 管理登录相关的状态,将登录后的 token 保存到本地缓存中。
const useLoginStore = defineStore('login', {
state: () => ({
id: '',
token: localCache.getCache('token') ?? '',
name: ''
}),
actions: {
async loginAccountAction(account: IAccount) {
// 账号登录,获取token等信息
const loginResult = await accountLoginRequest(account)
// console.log(loginResult)
this.id = loginResult.data.id
this.token = loginResult.data.token
this.name = loginResult.data.name
// 进行本地缓存
localCache.setCache('token', this.token)
}
}
})