一、设置localstoreage
1/先导出-存
export const setStore = (name, content, maxAge = null) => {
if (!global.window || !name) {
return
}
if (typeof content !== 'string') {
content = JSON.stringify(content)
}
//
const storage = global.window.localStorage
storage.setItem(name, content)
//最大日期
if (maxAge && !isNaN(parseInt(maxAge))) {
const timeout = parseInt(new Date().getTime() / 1000)
storage.setItem(`${name}_expire`, timeout + maxAge)
//设置当前时间+maxAge
}
}
2/声明 导出 存
export const getStore = name => {
//如果没有参数名就不往下走了
if (!global.window || !name) {
return
}
const content = window.localStorage.getItem(name)
const _expire = window.localStorage.getItem(`${name}_expire`)
//取的时候先判断_expire是否有,如果当前日期大于设置localstorage的日期,就不往下走
if (_expire) {
const now = parseInt(new Date().getTime() / 1000)
if (now > _expire) {
return
}
}
//如果小于就能取到这个值
try {
return JSON.parse(content)
} catch (e) {
return content
}
}
3/清空
export const clearStorage=name=>{
if(!global.window||!name){
return
}
localstorage.windows.removeItem(name)
}
二,运用
将VUEX中存储的值,存到localstorage中,这样就能在第一次加载的时候,将服务器上的静态数据快速存到本地localstorage中,而不用频繁请求接口去取数据
那什么时候去存localstorage呢?就是在第一次加载的时候,请求一次接口,将接口请求到的数据,存到本地
// 获取**枚举
getModuleEnums({ commit }) {
getData().then(function(d) {
if (d.code === '0' || d.code === 0) {
const dt = JSON.parse(JSON.stringify(d.data))
setStore(SPF.ModuleEnums, dt)
commit('SET_ModuleEnums', dt)
}
})
},
如何从localstorage中取数据
store.commit('SET_ModuleEnums', getStore(SPF.ModuleEnums))