predata.js
1.65 KB
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
78
79
80
import Vue from 'vue';
function getDataKey(method, params) {
return `${method}${Object.keys(params)
.filter(key => typeof params[key] !== 'undefined')
.sort()
.map(key => `${key}=${params[key]}`).join('&')}`;
}
function getPredata(key) {
return global.predatas.find(item => item.key === key);
}
function fetch($api) {
return function(url, params, options) {
if (process.env.VUE_ENV === 'server') {
return $api.get(url, params, options);
}
let ispredata = {
val: false
};
const dataKey = `predata_${getDataKey(url, params)}`;
const precall = (resolve) => {
return data => {
ispredata.val = true;
resolve(data);
};
};
const preData = getPredata(dataKey);
if (preData) {
return preData.value;
}
return new Promise(async(resolve, reject) => {
const call = precall(resolve);
Vue.$bus.$on(dataKey, call);
// await new Promise(r => {
// setTimeout(() => {
// r();
// }, 3000);
// });
return $api.get(url, params, options).then(data => {
Vue.$bus.$off(dataKey, call);
if (!ispredata.val) {
resolve(data);
}
}).catch(reject);
});
};
}
function init() {
if (!global.predatas) {
global.predatas = [];
}
const pushOrigin = global.predatas.push.bind(global.predatas);
global.predatas.push = function(item) {
if (item.key) {
Vue.$bus.$emit(item.key, item.value);
}
return pushOrigin(item);
};
}
export default ($api) => {
if (process.env.VUE_ENV !== 'server') {
init();
}
return {
fetch: fetch($api),
getpre: getPredata
};
};