useGetList.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import http from '/admin/support/http'
  2. import { provide, ref, unref } from 'vue'
  3. import { Code } from '/admin/enum/app'
  4. import Message from '/admin/support/message'
  5. const initLimit = 10
  6. const initPage = 1
  7. const initTotal = 10
  8. // get table list
  9. export function useGetList(path: string, isPaginate: boolean = true) {
  10. const data = ref<object>()
  11. const page = ref<number>(initPage)
  12. const limit = ref<number>(initLimit)
  13. const total = ref<number>(initTotal)
  14. const query = ref<object>({})
  15. if (isPaginate) {
  16. query.value = Object.assign({
  17. page: page.value,
  18. limit: limit.value,
  19. })
  20. }
  21. const loading = ref(true)
  22. // fetch list
  23. function getList() {
  24. // when table's data page >= 100, it will loading
  25. if (page.value >= 100) {
  26. loading.value = true
  27. }
  28. http
  29. .get(path, unref(query))
  30. .then(r => {
  31. closeLoading()
  32. if (r.data.code === Code.SUCCESS) {
  33. data.value = r.data
  34. // @ts-ignore
  35. total.value = data.value?.total
  36. } else {
  37. Message.error(r.data.message)
  38. }
  39. })
  40. .finally(() => {
  41. closeLoading()
  42. })
  43. }
  44. // close loading
  45. function closeLoading() {
  46. loading.value = false
  47. }
  48. // search
  49. function search() {
  50. getList()
  51. }
  52. // reset
  53. function reset() {
  54. resetPage()
  55. if (isPaginate) {
  56. query.value = Object.assign({ page: page.value, limit: limit.value })
  57. }
  58. getList()
  59. }
  60. // change page
  61. function changePage(p: number) {
  62. page.value = p
  63. // @ts-ignore
  64. query.value.page = p
  65. search()
  66. }
  67. function resetPage() {
  68. page.value = 1
  69. }
  70. // change limit
  71. function changeLimit(l: number) {
  72. limit.value = l
  73. resetPage()
  74. // @ts-ignore
  75. query.value.page = 1
  76. // @ts-ignore
  77. query.value.limit = l
  78. search()
  79. }
  80. // provider for paginate component
  81. provide('paginate', { page, limit, total, changePage, changeLimit })
  82. return { data, query, search, reset, loading }
  83. }