1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import Vue from 'vue'
import api from '@/api'
const state = {
dict: {},
queue: []
}
const mutations = {
SET_DICT: (state, { type, list }) => {
// 设置值:注意得用Vue.set方法
Vue.set(state.dict, type, list)
},
SET_QUEUE: (state, type) => {
state.queue.push(type)
},
DEL_QUEUE: (state, type) => {
// 找到并删除
for (let i = 0; i < state.queue.length; i++) {
const item = state.queue[i]
if (item === type) {
state.queue.splice(i, 1)
break
}
}
}
}
const actions = {
async getDictByType ({ dispatch, state }, type) {
/**
* 闭包特性。返回一个函数,该函数接收一个type参数。
* 同时由于闭包还持有state对象,故可以返回需要的值。
*/
await dispatch('dict', type)
var obj = JSON.parse(JSON.stringify(state.dict[type]))
return obj
},
// 缓存字典内容
dict ({ commit, state }, type) {
// 判断是否已经缓存过,缓存过后将不再获取数据
const isExistence = state.queue.some((item) => {
return item === 'dict/' + type
})
// 没有缓存则请求数据
if (!isExistence) {
// 在异步请求之前将该任务标记为已缓存(存入队列)
this.commit('cache/SET_QUEUE', 'dict/' + type)
return new Promise(async (resolve, reject) => {
await api.parameter.getArrayListByType({ typeId: type })
.then(({ data = {} }) => {
if (data) {
try {
this.commit('cache/SET_DICT', { type: type, list: data })
resolve(data)
} catch (error) {
reject(error)
}
} else {
reject('error')
}
}).catch(err => {
// 获取失败移除缓存队列
this.commit('cache/DEL_QUEUE', 'dict/' + type)
reject(err.response)
})
})
} else {
return state.dict[type]
}
}
}
export default {
namespaced: true,
state,
mutations,
actions
}