vuex 的数据一但浏览器刷新,就会重置。这对用户不友好,大部分用户都有刷新浏览器的习惯。可以数据存在localstore里面,localstore里面可以存放5mb大小数据,其实是非常多了。
定义一个类
class wdcLocalStore{
static set(key,value){
if(!localStore){
return
}
let t = value
try{
if(typeof value ==="object"){
t = JSON.stringify(t)
}
localStore.setItem(key,t)
}catch(e){
}
}
static get(key){
if(!localStore){
return
}
return localStore.getItem(key)
}
static getJson(key){
if(!localStore){
return
}
return JSON.parse(localStore.getItem(key))
}
static remove(key){
if(!localStore){
return
}
try{
localStore.removeItem(key)
}catch(e){
}
}
}
export default wdcLocalStore
在vuex导入并使用
import localstorage from '@/libs/localstorage';
export default {
namespaced: true,
state: { // 属性
appInfo:{
},
logInfo:{
},
appFirmware:{
}
},
actions: { // 类似于mutations,允许异步
currentAppInfo({state},obj) {
state.appInfo = obj
localstorage.set('appInfo',obj)
},
currentLogInfo({state},obj) {
state.logInfo = obj
localstorage.set('logInfo',obj)
},
currentAppFirmware({state},obj) {
state.appFirmware = obj
localstorage.set('appFirmware',obj)
},
}
};
在页面使用,判断一下存储的数据是否为undefined ,如果是就从localstroe中取出
if(this.appInfo.id===undefined){
this.currentAppInfo(localstorage.getJson('appInfo'))
}