使用vuex缓存数据,一步步优化自己的vuex-cache

发布时间:2019-08-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了使用vuex缓存数据,一步步优化自己的vuex-cache脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

需求:

  1. 请求接口之后,缓存当前接口的数据,下次请求同一接口时拿缓存数据,不再重新请求
  2. 添加缓存失效时间

cache使用Map来实现

  1. ES6 模块与 CommonJS 模块的差异
  • CommonJS 模块输出的是一个值的拷贝,ES6 模块输出的是值的引用。
  • CommonJS 模块是运行时加载,ES6 模块是编译时输出接口。

因为ESM输出的是值的引用,直接就是单例模式了

详细

export let cache = new Cache()

版本1

思路:
  1. 在vuex注册插件,插件会在每次mutations提交之后,判断要不要写入cache
  2. 在提交actions的时候判断是否有cache,有就拿cache里面的数据,然后把数据commIT给mutataios

注意: 在插件里面获取的mutations-tyPE是包含命名空间的,而在actions里面则是没有命名空间,需要补全。
/mutation-types.js

/**
 * 需要缓存的数据会在mutations-type后面添加-CACHED
 */
export const SET_HOME_INDEX = 'SET_HOME_INDEX-CACHED'

/modules/home/index.js


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.js

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.js

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函数,在里面里面判断是否需要缓存,缓存是否超时。

优化点:

  1. 把原本分散的cache操作统一放入到fetch
  2. 减少了对命名空间的操作
  3. 添加了缓存有效时间

/actions.js

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判断是需要缓存,还是请求接口

/**
 * 用这个函数就说明是需要进入缓存
 * @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
  }
}

脚本宝典总结

以上是脚本宝典为你收集整理的使用vuex缓存数据,一步步优化自己的vuex-cache全部内容,希望文章能够帮你解决使用vuex缓存数据,一步步优化自己的vuex-cache所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。