下图来源于cookie、localStorage 和 sessionStorage的区别及应用实例
既然localstorage无有效期,关闭浏览器还存在,那么用来存储用户的身份信息并不是太合适,先看一下B站中localstorage都存在了啥,原来把我搜索的记录都存在了下来。
因此用户登录之后的token信息,我还是存在cookie中,虽然后台还是会为token设置超时时间。
之前参考了一个网站,将菜单和权限存储在localstorage中,除非他很少变动。
多租户模式下,一个人可以拥有多个账套,打开不同页签,操作不同账套的数据,从上图看,应该存储在sessionStorage,例如
当前账套ID是16
看看http请求参数,与sessionStorage中存储的账套ID一致。
接着看另外一个账套
另外一个账套请求参数如下,与账套信息是匹配的
因此知道了,SaaS之类平台,租户信息应该存储在sessionStorage中,这样可以让用户操作不同账套,数据还不会错乱。
接下来再看状态管理pinia
,状态数据是存储在内存中,当你在页面使用鼠标邮件刷新,这个数据就会消失。
赋值是下面的方式,这种方式,在页面刷新的时候,就会丢失。
pinia
有持久化解决方案,Pinia学习-存储数据、修改数据以及持久化实现,不过写一个通用的存储模板后,不一定非得要这样一个组件,因为既然选择有一定周期的存储,一定是因为业务,既然业务存在,那么应该掌握好数据的生存周期,所以我的经验告诉我,我应该自行设置。
接下来附带了统一数据存取风格的代码
/* localStorage */
tool.local = {set(key, data, datetime = 0) {//加密if(sysConfig.LS_ENCRYPTION == "AES"){data = tool.crypto.AES.encrypt(JSON.stringify(data), sysConfig.LS_ENCRYPTION_key)}let cacheValue = {content: data,datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000}return localStorage.setItem(key, JSON.stringify(cacheValue))},get(key) {try {const value = JSON.parse(localStorage.getItem(key))if (value) {let nowTime = new Date().getTime()if (nowTime > value.datetime && value.datetime != 0) {localStorage.removeItem(key)return null;}//解密if(sysConfig.LS_ENCRYPTION == "AES"){value.content = JSON.parse(tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key))}return value.content}return null} catch (err) {return null}},remove(key) {return localStorage.removeItem(key)},clear() {return localStorage.clear()}
}/*sessionStorage*/
tool.session = {set(table, settings) {var _set = JSON.stringify(settings)return sessionStorage.setItem(table, _set);},get(table) {var data = sessionStorage.getItem(table);try {data = JSON.parse(data)} catch (err) {return null}return data;},remove(table) {return sessionStorage.removeItem(table);},clear() {return sessionStorage.clear();}
}/*cookie*/
tool.cookie = {set(name, value, config={}) {var cfg = {expires: null,path: null,domain: null,secure: false,httpOnly: false,...config}var cookieStr = `${name}=${escape(value)}`if(cfg.expires){var exp = new Date()exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000)cookieStr += `;expires=${exp.toGMTString()}`}if(cfg.path){cookieStr += `;path=${cfg.path}`}if(cfg.domain){cookieStr += `;domain=${cfg.domain}`}document.cookie = cookieStr},get(name){var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"))if(arr != null){return unescape(arr[2])}else{return null}},remove(name){var exp = new Date()exp.setTime(exp.getTime() - 1)document.cookie = `${name}=;expires=${exp.toGMTString()}`}
}