vue 如何设置localstoreage,及运用到项目中

一、设置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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值