zmc
2023-12-18 6c74bf912e251347714099a84585f825b32a1c08
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 接口数据的获取
import { onActivated, onDeactivated, ref, watch } from 'vue';
 
export function useFetchData(fetch) {
  // 分页信息
  const currentPage = ref(1);
  const totalPage = ref(1);
  const pageSize = ref(20);
  const total = ref(0);
  watch(currentPage, (nValue, oValue) => {
    if (nValue != oValue) {
      fetchData();
    }
  });
  watch(pageSize, (nValue, oValue) => {
    if (nValue != oValue) {
      fetchData();
    }
  });
 
  // 加载状态, 0: 加载完成; 1: 加载中; 2: 已全部加载; 3: 加载失败;
  const loadStatus = ref(0);
 
  // 数据获取
  function fetchData() {
    loadStatus.value = 1;
    fetch(currentPage.value, pageSize.value)
      .then((pageInfo) => {
        currentPage.value = pageInfo.currentPage;
        totalPage.value = pageInfo.totalPage;
        total.value = pageInfo.total;
 
        loadStatus.value = 0;
      })
      .catch(() => {
        loadStatus.value = 3;
      })
      .finally(() => {
        loadStatus.value = 2;
      });
  }
 
  return {currentPage, totalPage, pageSize, total, loadStatus, fetchData}
}