useInfinite.js 1.7 KB

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