利用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
})