如何的正确封装请求 和优雅的嵌入业务 (2)

稳定的嵌入业务

此处衔接上一篇文章

此处我们以 vue3 代码为例

Copy
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
}
}