useInfinite.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { ref, unref, onMounted, computed } from "vue";
  2. import { chatApi } from '@/api/chat';
  3. export const useInfinite = (path, props) => {
  4. const pageParams = ref({ pageNum: 1, pageSize: 20 });
  5. const queryParams = ref(props);
  6. const recordList = ref([]);
  7. const isFetching = ref(false);
  8. const counter = ref(0);
  9. const noMore = ref(false);
  10. // let isSwitchStatus = false;
  11. const isMore = computed(() => pageParams.value.pageNum * pageParams.value.pageSize < counter.value);
  12. const addHistoryRecord = record => {
  13. recordList.value.unshift(...record);
  14. }
  15. const onScrolltolower = async () => {
  16. if(unref(isFetching) || unref(noMore) ) return;
  17. isFetching.value = true;
  18. const { rows, total } = await initRecordData();
  19. recordList.value.push(...rows);
  20. counter.value = total;
  21. if (unref(isMore)) {
  22. pageParams.value.pageNum ++;
  23. } else {
  24. noMore.value = true;
  25. }
  26. isFetching.value = false;
  27. }
  28. const onReset = async () => {
  29. const { rows, total } = await initRecordData({pageNum:1, pageSize: (pageParams.value.pageNum * pageParams.value.pageSize) + 1});
  30. recordList.value = rows;
  31. counter.value = total;
  32. noMore.value = !unref(isMore)
  33. }
  34. // 重置请求
  35. const onRestore = async (params) => {
  36. pageParams.value = { pageNum: 1, pageSize: 20 };
  37. queryParams.value = { ...unref(queryParams), ...params };
  38. const { rows, total } = await initRecordData();
  39. // isSwitchStatus = true;
  40. recordList.value = rows;
  41. counter.value = total;
  42. // setTimeout(() => isSwitchStatus = false, 100);
  43. noMore.value = !isMore.value;
  44. }
  45. const initRecordData = async (params = {}) => {
  46. const reqParams = {
  47. ...unref(pageParams),
  48. ...unref(queryParams),
  49. ...params
  50. }
  51. return await chatApi.getRecordFetch(path, reqParams);
  52. }
  53. onMounted(() => onScrolltolower());
  54. return {
  55. recordList,
  56. isFetching,
  57. onScrolltolower,
  58. onReset,
  59. onRestore,
  60. addHistoryRecord
  61. }
  62. }