使用vuex緩存數(shù)據(jù)并優(yōu)化自己的vuex-cache
需求:
- 請求接口之后,緩存當前接口的數(shù)據(jù),下次請求同一接口時拿緩存數(shù)據(jù),不再重新請求
- 添加緩存失效時間
cache使用map來實現(xiàn)
ES6 模塊與 CommonJS 模塊的差異
- CommonJS 模塊輸出的是一個值的拷貝,ES6 模塊輸出的是值的引用。
- CommonJS 模塊是運行時加載,ES6 模塊是編譯時輸出接口。
因為esm輸出的是值的引用,直接就是單例模式了
export let cache = new Cache()
版本1
思路:
- 在vuex注冊插件,插件會在每次mutations提交之后,判斷要不要寫入cache
- 在提交actions的時候判斷是否有cache,有就拿cache里面的數(shù)據(jù),然后把數(shù)據(jù)commit給mutataios
注意: 在插件里面獲取的mutations-type是包含命名空間的,而在actions里面則是沒有命名空間,需要補全。
/mutation-types.js
/**
* 需要緩存的數(shù)據(jù)會在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)進入緩存取數(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標志的數(shù)據(jù)存入緩存,
* 現(xiàn)在key值是mutations-type
* 問題:
* 沒辦法區(qū)分不同參數(shù)query的請求,
*
* 方法1: 用每個mutations-type + payload的json格式為key來緩存數(shù)據(jù)
*/
function cachePlugin () {
return store => {
store.subscribe(({ type, payload }, state) => {
// 需要緩存的數(shù)據(jù)會在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
思路:直接包裝fetch函數(shù),在里面里面判斷是否需要緩存,緩存是否超時。
優(yōu)化點:
- 把原本分散的cache操作統(tǒng)一放入到fetch
- 減少了對命名空間的操作
- 添加了緩存有效時間
/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判斷是需要緩存,還是請求接口
/**
* 用這個函數(shù)就說明是需要進入緩存
* @param {*} api 請求的接口
* @param {*} queryArr 請求的參數(shù)
* @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()
// 時間戳綁定在數(shù)組的屬性上
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
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
基于Vue實現(xiàn)圖片在指定區(qū)域內移動的思路詳解
這篇文章主要介紹了基于Vue實現(xiàn)圖片在指定區(qū)域內移動,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-11-11
vue3.x中useRouter()執(zhí)行后返回值是undefined問題解決
這篇文章主要給大家介紹了關于vue3.x中useRouter()執(zhí)行后返回值是undefined問題的解決方法,文中通過代碼示例介紹的非常詳細,對大家學習或者使用vue3.x具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09
vue之保留小數(shù)點兩位小數(shù) 使用filters(過濾器)
這篇文章主要介紹了vue之保留小數(shù)點兩位小數(shù) 使用filters(過濾器),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
詳解webpack打包vue項目之后生成的dist文件該怎么啟動運行
這篇文章主要介紹了詳解webpack打包vue項目之后生成的dist文件該怎么啟動運行,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09

