vuex 缓存指定数据到本地24小时

vue yekong

数据大屏开发中,需要将vuex数据进行缓存,但是又不是永久缓存,而是只缓存24小时,这里将实现代码记录下来。

vuex 缓存token 24小时

const state = {
  token: localStorage.getItem('token') || null,
  tokenExpire: localStorage.getItem('tokenExpire') || null
}

const getters = {
  getToken: state => {
    let token = null
    try {
      if (new Date().getTime() > state.tokenExpire) {
        localStorage.removeItem('token')
        localStorage.removeItem('tokenExpire')
      } else {
        token = JSON.parse(state.token)
      }
    } catch (err) {
      console.log('getToken-err', err)
    }
    return token
  },
}

const actions = {
  setToken({ commit }, token) {
    const t = JSON.stringify(token)
    const expireTime = new Date().getTime() + 24 * 60 * 60 * 1000 // 24 hours later
    localStorage.setItem('token', t)
    localStorage.setItem('tokenExpire', expireTime)
    commit('SET_TOKEN', t)
    commit('SET_TOKEN_EXPIRE', expireTime)
  },
  removeToken({ commit }) {
    localStorage.removeItem('token')
    localStorage.removeItem('tokenExpire')
    commit('REMOVE_TOKEN')
    commit('REMOVE_TOKEN_EXPIRE')
  }
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_TOKEN_EXPIRE(state, expireTime) {
    state.tokenExpire = expireTime
  },
  REMOVE_TOKEN(state) {
    state.token = null
  },
  REMOVE_TOKEN_EXPIRE(state) {
    state.tokenExpire = null
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}

喜欢