UNPKG

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

Version:
111 lines (110 loc) 2.71 kB
import { watch, onBeforeUnmount } from "vue"; import useState from "../../_hooks/use-state.js"; import { debounce } from "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 = debounce(fetchList, 200); watch(() => pageInfo.value.current, () => { fetchListDebounce(); }); watch(() => pageInfo.value.pageSize, () => { if (pageInfo.value.current) { fetchListDebounce(); } setPageInfo({ ...pageInfo.value, current: 1 }); }); watch(options.effects, () => { fetchListDebounce(); }, { immediate: true, deep: true }); 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 }) }; }; export { useFetchData as default };