使用vuex緩存數據,一步步優化本身的vuex-cache

需求:

  1. 請求接口以後,緩存當前接口的數據,下次請求同一接口時拿緩存數據,再也不從新請求
  2. 添加緩存失效時間

cache使用map來實現

  1. ES6 模塊與 CommonJS 模塊的差別
  • CommonJS 模塊輸出的是一個值的拷貝,ES6 模塊輸出的是值的引用。
  • CommonJS 模塊是運行時加載,ES6 模塊是編譯時輸出接口。

由於esm輸出的是值的引用,直接就是單例模式了javascript

詳細html

export let cache = new Cache()

版本1

思路:
  1. 在vuex註冊插件,插件會在每次mutations提交以後,判斷要不要寫入cache
  2. 在提交actions的時候判斷是否有cache,有就拿cache裏面的數據,而後把數據commit給mutataios

注意: 在插件裏面獲取的mutations-type是包含命名空間的,而在actions裏面則是沒有命名空間,須要補全。
/mutation-types.jsvue

/**
 * 須要緩存的數據會在mutations-type後面添加-CACHED
 */
export const SET_HOME_INDEX = 'SET_HOME_INDEX-CACHED'

/modules/home/index.jsjava

const actions = {
  /**
   * @description 若是有緩存,就返回把緩存的數據,傳入mutations,
   * 沒有緩存就從接口拿數據,存入緩存,把數據傳入mutations
   */
  async fetchAction ({commit}, {mutationType, fetchData, oPayload}) {
    // vuex開啓了命名空間,所這裏從cachekey要把命名空間前綴 + type + 把payload格式化成JSON
    const cacheKey = NAMESPACE + mutationType + JSON.stringify(oPayload)
    const cacheResponse = cache.get(cacheKey || '')
    if (!cacheResponse) {
      const [err, response] = await fetchData()
      if (err) {
        console.error(err, 'error in fetchAction')
        return false
      }
      commit(mutationType, {response: response, oPayload})
    } else {
      console.log('已經進入緩存取數據!!!')
      commit(mutationType, {response: cacheResponse, oPayload})
    }
  },
  loadHomeData ({ dispatch, commit }) {
    dispatch(
      'fetchAction',
      {
        mutationType: SET_HOME_INDEX,
        fetchData: api.index,
      }
    )
  }
}

const mutations = {
  [SET_HOME_INDEX] (state, {response, oPayload}) {},
}

const state = {
  indexData: {}
}

export default {
  namespaced: NAMESPACED,
  actions,
  state,
  getters,
  mutations
}
編寫插件,在這裏攔截mutations,判斷是否要緩存

/plugin/cache.jsios

import cache from 'src/store/util/CacheOfStore'
// import {strOfPayloadQuery} from 'src/store/util/index'
/**
 * 在每次mutations提交以後,把mutations-type後面有CACHED標誌的數據存入緩存,
 * 如今key值是mutations-type
 * 問題:
 * 沒辦法區分不一樣參數query的請求,
 *
 * 方法1: 用每一個mutations-type + payload的json格式爲key來緩存數據
 */
function cachePlugin () {
  return store => {
    store.subscribe(({ type, payload }, state) => {
      // 須要緩存的數據會在mutations-type後面添加CACHED
      const needCache = type.split('-').pop() === 'CACHED'
      if (needCache) {
        // 這裏的type會自動加入命名空間因此 cacheKey = type + 把payload格式化成JSON
        const cacheKey = type + JSON.stringify(payload && payload.oPayload)
        const cacheResponse = cache.get(cacheKey)
        // 若是沒有緩存就存入緩存
        if (!cacheResponse) {
          cache.set(cacheKey, payload.response)
        }
      }
      console.log(cache)
    })
  }
}
const plugin = cachePlugin()
export default plugin

store/index.jsgit

import Vue from 'vue'
import Vuex from 'vuex'
import home from './modules/home'
import cachePlugin from './plugins/cache'

Vue.use(Vuex)
const store = new Vuex.Store({
  modules: {
    home,
    editActivity,
    editGuide
  }
  plugins: [cachePlugin]
})

export default store

版本2

思路:
  1. 直接包裝fetch函數,在裏面裏面判斷是否須要緩存,緩存是否超時。

優化點:es6

  1. 把本來分散的cache操做統一放入到fetch
  2. 減小了對命名空間的操做
  3. 添加了緩存有效時間

/actions.jsvuex

const actions = {
  async loadHomeData ({ dispatch, commit }, oPayload) {
    commit(SET_HOME_LOADSTATUS)
    const [err, response] = await fetchOrCache({
      api: api.index,
      queryArr: oPayload.queryArr,
      mutationType: SET_HOME_INDEX
    })
    if (err) {
      console.log(err, 'loadHomeData error')
      return [err, response]
    }
    commit(SET_HOME_INDEX, { response })
    return [err, response]
  }
}

/在fetchOrCache判斷是須要緩存,仍是請求接口json

/**
 * 用這個函數就說明是須要進入緩存
 * @param {*} api 請求的接口
 * @param {*} queryArr 請求的參數
 * @param {*} mutationType 傳入mutationType做爲cache的key值
 */
export async function fetchOrCache ({api, queryArr, mutationType, diff}) {
  // 這裏是請求接口
  const fetch = httpGet(api, queryArr)
  const cachekey = `${mutationType}:${JSON.stringify(queryArr)}`
  if (cache.has(cachekey)) {
    const obj = cache.get(cachekey)
    if (cacheFresh(obj.cacheTimestemp, diff)) {
      return cloneDeep(obj)
    } else {
      // 超時就刪除
      cache.delete(cachekey)
    }
  }
  // 不取緩存的處理
  let response = await fetch()
  // 時間戳綁定在數組的屬性上
  response.cacheTimestemp = Date.now()
  cache.set(cachekey, response)
  // 返回cloneDeep的對象
  return cloneDeep(response)
}
/**
 * 判斷緩存是否失效
 * @param {*} diff 失效時間差,默認15分鐘=900s
 */
const cacheFresh = (cacheTimestemp, diff = 900) => {
  if (cacheTimestemp) {
    return ((Date.now() - cacheTimestemp) / 1000) <= diff
  } else {
    return true
  }
}
相關文章
相關標籤/搜索