利用vuex 做个简单的前端缓存

利用vuex 做个简单的前端缓存

vuex 使用vuex-persistedstate 做持久化存储时无法保存 map,这就尴尬了

在javascript 中,object也是一种字典,object 的key 具有唯一性 使用object 存储也是可行的

代码如下

import Vue from 'vue'

const state = {
  dictionary: {}
}

const mutations = {
  SET: (state, data) => {
    Vue.set(state.dictionary, data.cacheKey, data.cacheValue)
  },
  REMOVE: (state, data) => {
    Vue.delete(state.dictionary, data.cacheKey)
  },
  CLEAR: state => {
    state.dictionary = {}
  }
}

const actions = {
  get({ state }, data) {
    return state.dictionary[data]
  },
  set({ commit }, data) {
    commit('SET', data)
  },
  remove({ commit }, data) {
    commit('REMOVE', data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

使用

获取缓存

      let cacheKey = `${this.wwa1}-${this.wwab1}`

      let value = await this.$store.dispatch('cache/get', cacheKey)

存储

      await this.$store.dispatch('cache/set', {
        cacheKey: cacheKey,
        cacheValue: data
      })
posted @ 2021-05-26 17:15  Pursue`  阅读(332)  评论(0编辑  收藏  举报