1.localStorage缓存
过期策略:localstorage永久存储,不过期,除非手动删除,sessionstorage在重启浏览器、关闭页面或新开页面时失效。
1.1添加缓存
localStorage.setItem("name","value");
export function addLocalStorage (name, varietiesCode, productNameList) {
let getStorage = localStorage.getItem(name)
if (getStorage != null) {
//将JSON格式字符串转换为js对象
let jsonStorage = JSON.parse(getStorage)
let proudcList = varietiesCode
//查看品种是否存在
let index = jsonStorage.findIndex((x) => x.code === proudcList)
if (index >= 0) {
//若存在则删除掉该项
jsonStorage.splice(index, 1)
}
let goModel = { code: varietiesCode, data: [] }
goModel.data = productNameList
jsonStorage.push(goModel)
localStorage.setItem(name, JSON.stringify(jsonStorage))
} else {
let goModel = { code: varietiesCode, data: [] }
goModel.data = productNameList
localStorage.setItem(name, JSON.stringify([goModel]))
}
}
huancun() {
//添加缓存
addLocalStorage(
"landingsVarietiesCode",
this.dataForm.varietiesCode,
this.dataForm.productNameList
);
},
JSON.parse()方法将JSON格式字符串转换为js对象(属性名没有双引号)。
解析前要保证数据是标准的JSON格式,否则会解析出错。
var jstr = '{"name":"wust", "url":"www.wust.edu.cn", "age":120}'
var obj = JSON.parse(jstr);
// 结果 obj= { name:"wust", url:"www.wust.edu.cn", age:120 }
1.2 读取缓存
JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。
//读取缓存
let getStorage = localStorage.getItem(name)
if (getStorage != "" && getStorage != null) {
let jsonStorage = JSON.parse(getStorage)
let json = jsonStorage.filter(
(x) => x.code == varietiesCode
);
if (json.length > 0) {
if (json[0].data.length > 0)
return json[0].data
else
return []
}
return []
}
return []
filter()方法会创建一个新数组,原数组的
每个元素传入回调函数中,回调函数中有return返回值,若返回值为true,这个元素保存到新数组中;若返回值为false,则该元素不保存到新数组中;原数组不发生改变。