我可能会这样写:
```typescript
type Role = { id: string; name: string };
function usePage<T>() {
const role = ref<Role | null>(null)
const loading = ref(false);
const page = reactive({ current: 1, size: 10 });
const uri = computed(() => `/api/b?page=${page.current}&size=${page.size}`);
const { data, error, execute } = useFetch(uri, { immediate: false }).json<T>()
// 防抖避免快速点击翻页按钮发送无效请求
const onLoadPageData = debounce(async () => {
try {
loading.value = true;
await initRole();
await execute();
} finally {
loading.value = false;
}
}, 200)
async function initRole() {
if (role.value) return;
const { data, error } = await useFetch("/api/a").json<Role>();
if (error.value) {
/** @
todo error handler */
} else {
role.value = data.value;
onLoadPageData();
}
}
initRole();
watch(page, onLoadPageData, { immediate: true });
return { page, data, error, loading, onLoadPageData }
}
```