useInfiniteScroll.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { inject, onBeforeUnmount, onMounted, ref, watch } from 'vue'
  2. import { getProduct } from '../api'
  3. import emitter from '/@/utils/emitter'
  4. export default function useInfiniteScroll() {
  5. const profile = <any>inject('profile')
  6. const parentloading = ref(false)
  7. const productSelect = ref('')
  8. emitter.on('ExchangeProduct-productSelect', (value: any) => {
  9. productSelect.value = value
  10. })
  11. const searchInp = ref('')
  12. emitter.on('ExchangeProduct-searchInp', (value: any) => {
  13. searchInp.value = value.value
  14. })
  15. const allData = ref([])
  16. let currentPage = ref(1)
  17. let total = 0
  18. let limit = 10
  19. function load() {
  20. if (currentPage.value * limit < total) {
  21. currentPage.value++
  22. fetchProduct()
  23. }
  24. }
  25. async function fetchProduct() {
  26. parentloading.value = true
  27. const query = {
  28. profileId: profile.value.profile_id,
  29. productlineId: productSelect.value,
  30. page: currentPage.value,
  31. limit: limit,
  32. searchItem: searchInp.value,
  33. }
  34. try {
  35. const res = await getProduct(query)
  36. if (res && res.data) {
  37. const newData = res.data
  38. if (currentPage.value > 1) {
  39. allData.value.push(...newData)
  40. } else {
  41. allData.value = newData
  42. }
  43. total = res.total
  44. }
  45. } catch (error) {
  46. console.log('error:', error)
  47. } finally {
  48. parentloading.value = false
  49. emitter.emit('ExchangeProduct-allData', allData)
  50. }
  51. }
  52. onMounted(() => {
  53. fetchProduct()
  54. })
  55. onBeforeUnmount(() => {
  56. emitter.all.clear()
  57. })
  58. return { allData, parentloading, currentPage, load, fetchProduct }
  59. }