背景
在使用vite+vue3+axios+vue4 进行项目开发时,我们都知道vuex中的数据是保存在内存当中的,当浏览器刷新数据就消失了,需要对数据进行持久化存储,存储比较容易实现,当获取持久化的数据时遇到了困难,还是因为ts不太熟,正在学习过程中,记录一下,后期有好方案再更新一下
持久化存储vuex中的数据,使用泛型对数据进行约束,对于存储过程来说,因为我们不关心返回的数据格式,使用void 返回即可
// utils/storage.ts
// 全局配置文件
import config from "@/config"
// 定义存储数据接口
interface ILocalStorage<T> {
dataType: string;
content: T;
dataTime: number
}
// 数据持久化
/**
* 存储localStorage
* @param key
* @param content
*/
export const setStore = <T>(key: string, content: T): void => {
let name = `${config.key}-${key}`
let obj: ILocalStorage<T> = {
dataType: typeof content, // 这里只对引用类型和基本类型做了区分,没有详细区分引用类型
content,
dataTime: new Date().getTime()
}
window.localStorage.setItem(name, JSON.stringify(obj))
}
// 调用
interface Imenu{
path:string;
component:string
}
const menuList:Array<Imenu> = [
{
path:'/login',
component:'Login'
},
{
path:'/about',
component:'About'
}
]
interface IScore {
chinese:number;
math:number
}
const score:IScore = {
chinese:85,
math:96
}
setStore<string>('name','管理员')
setStore<number>('age',36)
setStore<Imenu[]>('menu',menuList)
setStore<IScore>('score',score)
通过上面的setStore 就可以实现数据的持久化存储,其实这里没有必要使用泛型去约束,因为返回为void,实际使用时改成any即可
获取持久化数据
获取持久化存储数据,因为获取数据后对数据操作想要得到ts类型提示,必须对返回的数据进行约束,使用ts最大的好处就是类型系统,能让我们再编译之前就发现代码错误,而不是编译之后才发现代码错误,大大增加了开发效率
- 根据setStore 存储数据时进行JSON.stringify转换为字符串,localStorage.getItem 获取数据只有两种类型,如果有对应的密钥,返回肯定是字符串,没有的话返回null
const value: string | null = localStorage.getItem(name)
- 对数据进行处理,
// 使用js语法
/**
* 获取存储到localStorage的值
* @param key
* @returns
*/
export const getStore = <T>(key: string): T | null => {
const name = `${config.key}-${key}`
const value: string | null = localStorage.getItem(name)
// 没有获取到值,直接返回null
if (!value) return null
// 对有值的进行JSON.parse()转换为Javascript对象,这里可以不用try...catch进行异常捕获,因为根据存储格式这里都是可以正常进行解析的
const store: ILocalStorage<T> = JSON.parse(value)
return store.content
}
// 调用
interface Imenu {
path: string
component: string
}
const menuList: Imenu[] = [
{
path: '/login',
component: 'Login'
},
{
path: '/about',
component: 'About'
}
]
setStore<Imenu[]>('menu', menuList)
const menu = getStore<Imenu[]>('menu') || [] // 这里需要对返回为null的处理,否则下面的遍历会有问题
menu.forEach((item) => {
console.log(item.path) // 这里就可以得到类型提示了
})
网友评论