使用vuex緩存數(shù)據(jù)并優(yōu)化自己的vuex-cache
需求:
- 請(qǐng)求接口之后,緩存當(dāng)前接口的數(shù)據(jù),下次請(qǐng)求同一接口時(shí)拿緩存數(shù)據(jù),不再重新請(qǐng)求
- 添加緩存失效時(shí)間
cache使用map來實(shí)現(xiàn)
ES6 模塊與 CommonJS 模塊的差異
- CommonJS 模塊輸出的是一個(gè)值的拷貝,ES6 模塊輸出的是值的引用。
- CommonJS 模塊是運(yùn)行時(shí)加載,ES6 模塊是編譯時(shí)輸出接口。
因?yàn)閑sm輸出的是值的引用,直接就是單例模式了
export let cache = new Cache()
版本1
思路:
- 在vuex注冊(cè)插件,插件會(huì)在每次mutations提交之后,判斷要不要寫入cache
- 在提交actions的時(shí)候判斷是否有cache,有就拿cache里面的數(shù)據(jù),然后把數(shù)據(jù)commit給mutataios
注意: 在插件里面獲取的mutations-type是包含命名空間的,而在actions里面則是沒有命名空間,需要補(bǔ)全。
/mutation-types.js
/** * 需要緩存的數(shù)據(jù)會(huì)在mutations-type后面添加-CACHED */ export const SET_HOME_INDEX = 'SET_HOME_INDEX-CACHED' /modules/home/index.js const actions = { /** * @description 如果有緩存,就返回把緩存的數(shù)據(jù),傳入mutations, * 沒有緩存就從接口拿數(shù)據(jù),存入緩存,把數(shù)據(jù)傳入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('已經(jīng)進(jìn)入緩存取數(shù)據(jù)?。?!') 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標(biāo)志的數(shù)據(jù)存入緩存, * 現(xiàn)在key值是mutations-type * 問題: * 沒辦法區(qū)分不同參數(shù)query的請(qǐng)求, * * 方法1: 用每個(gè)mutations-type + payload的json格式為key來緩存數(shù)據(jù) */ function cachePlugin () { return store => { store.subscribe(({ type, payload }, state) => { // 需要緩存的數(shù)據(jù)會(huì)在mutations-type后面添加CACHED const needCache = type.split('-').pop() === 'CACHED' if (needCache) { // 這里的type會(huì)自動(dòng)加入命名空間所以 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
思路:直接包裝fetch函數(shù),在里面里面判斷是否需要緩存,緩存是否超時(shí)。
優(yōu)化點(diǎn):
- 把原本分散的cache操作統(tǒng)一放入到fetch
- 減少了對(duì)命名空間的操作
- 添加了緩存有效時(shí)間
/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判斷是需要緩存,還是請(qǐng)求接口
/** * 用這個(gè)函數(shù)就說明是需要進(jìn)入緩存 * @param {*} api 請(qǐng)求的接口 * @param {*} queryArr 請(qǐng)求的參數(shù) * @param {*} mutationType 傳入mutationType作為cache的key值 */ export async function fetchOrCache ({api, queryArr, mutationType, diff}) { // 這里是請(qǐng)求接口 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 { // 超時(shí)就刪除 cache.delete(cachekey) } } // 不取緩存的處理 let response = await fetch() // 時(shí)間戳綁定在數(shù)組的屬性上 response.cacheTimestemp = Date.now() cache.set(cachekey, response) // 返回cloneDeep的對(duì)象 return cloneDeep(response) } /** * 判斷緩存是否失效 * @param {*} diff 失效時(shí)間差,默認(rèn)15分鐘=900s */ const cacheFresh = (cacheTimestemp, diff = 900) => { if (cacheTimestemp) { return ((Date.now() - cacheTimestemp) / 1000) <= diff } else { return true } }
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue.js 表格分頁ajax 異步加載數(shù)據(jù)
Vue.js通過簡潔的API提供高效的數(shù)據(jù)綁定和靈活的組件系統(tǒng).這篇文章主要介紹了vue.js 表格分頁ajax 異步加載數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2016-10-10使用Vue實(shí)現(xiàn)帶拖動(dòng)和播放功能的時(shí)間軸
這篇文章主要為大家詳細(xì)介紹了如何使用Vue實(shí)現(xiàn)帶拖動(dòng)和播放功能的時(shí)間軸,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03Vue Vine實(shí)現(xiàn)一個(gè)文件中寫多個(gè)組件的方法(最近很火)
Vue Vine提供了全新Vue組件書寫方式,主要的賣點(diǎn)是可以在一個(gè)文件里面寫多個(gè)vue組件,Vue Vine是一個(gè)vite插件,vite解析每個(gè)模塊時(shí)都會(huì)觸發(fā)插件的transform鉤子函數(shù),本文介紹Vue Vine是如何實(shí)現(xiàn)一個(gè)文件中寫多個(gè)組件,感興趣的朋友一起看看吧2024-07-07詳解vue中使用vue-quill-editor富文本小結(jié)(圖片上傳)
這篇文章主要介紹了詳解vue中使用vue-quill-editor富文本小結(jié)(圖片上傳),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04vue生命周期beforeDestroy和destroyed調(diào)用方式
這篇文章主要介紹了vue生命周期beforeDestroy和destroyed調(diào)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06vue調(diào)試工具vue-devtools的安裝全過程
這篇文章主要介紹了vue調(diào)試工具vue-devtools的安裝全過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06在vue-cli搭建的項(xiàng)目中增加后臺(tái)mock接口的方法
這篇文章主要介紹了在vue-cli搭建的項(xiàng)目中增加后臺(tái)mock接口的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-04-04