useTabbar.js
2.75 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { computed, reactive, readonly } from 'vue';
import { getTabbarConfigAPI } from './tabbar.api';
import {
getDefaultTabbarActiveColor,
getDefaultTabbarItem,
getHomeOnlyTabbarItems,
normalizeTabbarColor,
normalizeTabbarKey,
normalizeTabbarPayload,
resolveTabbarTargetUrl,
} from './tabbar.utils';
const state = reactive({
tabItems: getHomeOnlyTabbarItems(),
activeColor: getDefaultTabbarActiveColor(),
loaded: false,
loading: false,
loadMode: 'api',
});
let tabbarRequestPromise = null;
const applyFallbackItems = () => {
state.tabItems = getHomeOnlyTabbarItems();
state.activeColor = getDefaultTabbarActiveColor();
};
const resolveLoadMode = (options = {}) => (options.useMock ? 'mock' : 'api');
export const fetchTabbarConfig = async (force = false, options = {}) => {
const loadMode = resolveLoadMode(options);
if (!force && state.loaded && state.loadMode === loadMode) {
return state.tabItems;
}
if (state.loading && tabbarRequestPromise) {
return tabbarRequestPromise;
}
state.loading = true;
tabbarRequestPromise = (async () => {
try {
if (loadMode === 'mock') {
state.tabItems = normalizeTabbarPayload(options.mockData);
state.activeColor = normalizeTabbarColor(options.mockData);
state.loadMode = loadMode;
return state.tabItems;
}
const response = await getTabbarConfigAPI();
if (response?.code === 1) {
state.tabItems = normalizeTabbarPayload(response?.data);
state.activeColor = normalizeTabbarColor(response?.data);
} else {
applyFallbackItems();
}
state.loadMode = loadMode;
} catch (error) {
console.error('获取底部导航配置失败:', error);
applyFallbackItems();
state.loadMode = loadMode;
} finally {
state.loaded = true;
state.loading = false;
tabbarRequestPromise = null;
}
return state.tabItems;
})();
return tabbarRequestPromise;
};
export const ensureTabbarLoaded = (options = {}) => {
const loadMode = resolveLoadMode(options);
if (state.loaded && state.loadMode === loadMode) {
return Promise.resolve(state.tabItems);
}
return fetchTabbarConfig(false, options);
};
export const useJlsTabbar = () => {
const visibleTabItems = computed(() => state.tabItems.filter((item) => item.visible !== false));
const getTabItem = (key) => {
const normalizedKey = normalizeTabbarKey(key);
return state.tabItems.find((item) => item.key === normalizedKey) || getDefaultTabbarItem(normalizedKey);
};
return {
state: readonly(state),
visibleTabItems,
getTabItem,
activeColor: computed(() => state.activeColor),
ensureLoaded: ensureTabbarLoaded,
fetchTabbarConfig,
resolveTargetUrl: resolveTabbarTargetUrl,
};
};