前言:在日常开发中,我们的任务需求依赖于本地存储(localStorage,sessionStorage),sessionStorage 和 localStorage 的用法基本一致,引用类型的值要转换成JSON。下面我们在基于Vue框架的基础之上,简单封装一个localStorage的轮子。
1.在utils(公共方法文件夹)中新建一个cache.js文件
2.代码写入公共方法并导出
// 定义我们项目专有本地存储作用域
const LOC_NAME_SPACE = 'demoFunction';
class LocalCache {
// 上传
setCache(key,value) {
// 判断项目是否存在本地存储
let storage = window.localStorage.getItem(LOC_NAME_SPACE);
if(!storage){
storage = {};
}else{
storage = JSON.parse(storage);
}
storage[key] = value;
// 服务器一般接受的形式为字符串,所以转换成字符串
window.localStorage.setItem(LOC_NAME_SPACE, JSON.stringify(storage));
}
// 获取
getCache(key,def) { //def是默认值
let storage = window.localStorage.getItem(LOC_NAME_SPACE);
if(!storage){
return def;
}
// 服务器一般发送回字符串数据,我们解析成正常数据
storage = JSON.parse(storage)
let result = storage[key];
return result || def;
}
// 删除
deleteCache(key) {
let storage = window.localStorage.getItem(LOC_NAME_SPACE);
if(!storage){
return;
}
storage = JSON.parse(storage)
window.localStorage.removeItem(storage[key])
}
// 清空
clearCache() {
let storage = window.localStorage.getItem(LOC_NAME_SPACE);
window.localStorage.removeItem(storage)
}
}
export default new LocalCache()
3.使用
可以在main.js注册全局引用,也可以在你需要使用的文件中单独引用
import LocalCache from 'utils/cache';
// set存储数据
LocalCache.setCache(
'user_id',
res.user_id ? res.user_id : ''
);
// get请求数据
LocalCache.getCache('user_id',' 默认值');
// delete删除单条数据
LocalCache.deleteCache('user_id');
// clear清空全部数据
LocalCache.clearCache()
水平有限,还不能写到尽善尽美,希望大家多多交流,跟春野一同进步!!!