SnowGuest

SnowGuest

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

How to properly encapsulate requests and elegantly embed business (2)

Stable Embedding Business

This section is connected to the previous article.

Here we take vue3 code as an example

import { ref, reactive } from "vue-demi";
import request from "end of the previous article";
import type { AxiosRequestConfig } from "axios";


/* Specify a unique key */
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)
      });
      /* If the number of retrieved items is less than the size of pageSize, it can be considered as reaching the end */
      if (pageSize > result.data.length) finish.value = true;
    } catch (error) {
      console.error(error)
    } finish {
      loading.value = false
    }
  }
  proxyRequest()
  return {
    listMap,
    pageNum,
    pageSize,
    finish,
    loading
  }
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.