SnowGuest

SnowGuest

这里是 SnowGuest的博客站点,只会记录一些有意思的日常事
bilibili
github

如何的正確封裝請求和優雅的嵌入業務 (2)

穩定的嵌入業務#

此處衔接上一篇文章

此處我們以 vue3 代碼為例

import { ref, reactive } from "vue-demi";
import request from "上一篇文章末尾";
import type { AxiosRequestConfig } from "axios";


/* 指定唯一鍵 */
function getPaging<T>(conf: AxiosRequestConfig, k: keyof T) {
  const listMap = reactive<Map<T[k], T>>(new Map());
  const pageNum = ref(0);
  const pageSize = ref(1);
  const finish = ref(false);
  const loading = ref(false);
  const to = async (current: number) => {
    if (finish.value) throw new Error("no more");
    pageNum.value = current;
    await proxyRequest()
  }
  const next = async () => {
    await to(pageNum.value + 1);
  }
  const base = async () => {
    await to(pageNum.value - 1);
  }
  async function proxyRequest() {
    try {
      loading.value = true
      const result = await request({
        ...conf,
        data: Object.assign(conf.data, {
          pageNum: pageNum.value,
          pageSize: pageSize.value
        })
      });
      result.data.forEach(e => {
        listMap.set(e[k], e)
      });
      /* 查詢的到的條數少於pageSize的大小即可視為到底了 */
      if (pageSize > result.data.length) finish.value = true;
    } catch (error) {
      console.error(error)
    } finish {
      loading.value = false
    }
  }
  proxyRequest()
  return {
    listMap,
    pageNum,
    pageSize,
    finish,
    loading
  }
}
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。