useInfinite.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 = (params) => {
  33. console.log( "params", params );
  34. pageParams.value = { page: 1, pageSize: 20 };
  35. initRecordData(params);
  36. }
  37. const initRecordData = async (params = {}) => {
  38. const reqParams = {
  39. ...props,
  40. ...params,
  41. ...pageParams.value
  42. }
  43. return await chatApi.getRecordFetch(path, reqParams);
  44. }
  45. onMounted(() => onScrolltolower());
  46. return {
  47. recordList,
  48. isFetching,
  49. onScrolltolower,
  50. onReset,
  51. onRestore,
  52. addHistoryRecord
  53. }
  54. }