UNPKG

@arco-vue-pro-components/pro-components

Version:
112 lines (111 loc) 2.72 kB
"use strict"; var vue = require("vue"); var useState = require("../../_hooks/use-state.js"); var lodash = require("lodash"); const mergeOptionAndPageInfo = (pageInfo) => { if (pageInfo) { const { current, defaultCurrent, pageSize, defaultPageSize } = pageInfo; return { current: current || defaultCurrent || 1, pageSize: pageSize || defaultPageSize || 20 }; } return { current: 1, pageSize: 20 }; }; const useFetchData = (getData, props, emit, options) => { const [list, setList] = useState((props == null ? void 0 : props.defaultData) || []); const [loading, setLoading] = useState(void 0); const [pageInfo, setPageInfo] = useState(mergeOptionAndPageInfo(options.pageInfo)); const fetchList = async (isAppend) => { if (loading.value || !getData) { return []; } setLoading(true); try { const { data = [], success, total: dataTotal = 0, ...rest } = await getData({ current: pageInfo.value.current, pageSize: pageInfo.value.pageSize }) || {}; if (success !== false) { if (isAppend && list) { setList([...list.value, ...data]); } else { setList(data); } setPageInfo({ ...pageInfo.value, total: dataTotal }); } if (emit) { emit("load", data, dataTotal, rest); } } catch (e) { if (emit) { emit("requestError", e); } } finally { requestAnimationFrame(() => { setLoading(false); }); } return []; }; const fetchListDebounce = lodash.debounce(fetchList, 200); vue.watch(() => pageInfo.value.current, () => { fetchListDebounce(); }); vue.watch(() => pageInfo.value.pageSize, () => { if (pageInfo.value.current) { fetchListDebounce(); } setPageInfo({ ...pageInfo.value, current: 1 }); }); vue.watch(options.effects, () => { fetchListDebounce(); }, { immediate: true, deep: true }); vue.onBeforeUnmount(() => { fetchListDebounce.cancel(); }); return { data: list, setDataSource: setList, loading, reload: async () => { await fetchListDebounce(); }, pageInfo, reset: () => { var _a, _b; setPageInfo({ current: ((_a = options.pageInfo) == null ? void 0 : _a.defaultCurrent) || 1, pageSize: ((_b = options.pageInfo) == null ? void 0 : _b.defaultPageSize) || 20 }); }, getPopupContainer: () => options.getPopupContainer(), setPageInfo: (info) => setPageInfo({ ...pageInfo.value, ...info }) }; }; module.exports = useFetchData;