hook: useApi

This commit is contained in:
Rewrite0
2023-05-31 17:34:39 +08:00
parent b9a0777dcf
commit ed20bfc6f0
2 changed files with 53 additions and 2 deletions

51
src/hooks/useApi.ts Normal file
View File

@@ -0,0 +1,51 @@
type AnyAsyncFuntion<TData = any> = (...args: any[]) => Promise<TData>;
export function useApi<
TError = any,
TApi extends AnyAsyncFuntion = AnyAsyncFuntion,
TData = ReturnType<TApi>
>(
api: TApi,
options?: {
message?: {
success?: string;
error?: string;
};
}
) {
const data = ref<TData>();
const isLoading = ref(false);
const fetchResult = createEventHook<TData>();
const fetchError = createEventHook<TError>();
const message = useMessage();
function execute(...params: Parameters<TApi>) {
isLoading.value = true;
api(...params)
.then((res) => {
data.value = res;
fetchResult.trigger(res);
options?.message?.success && message.success(options.message.success);
})
.catch((err) => {
fetchError.trigger(err);
options?.message?.error && message.error(options.message.error);
})
.finally(() => {
isLoading.value = false;
});
}
return {
data,
isLoading,
execute,
onResult: fetchResult.on,
onError: fetchError.on,
};
}

View File

@@ -80,11 +80,11 @@ definePage({
@click="() => open(i)"
></ab-bangumi-card>
<AbEditRule
<ab-edit-rule
v-model:show="editRule.show"
v-model:rule="editRule.item"
@delete="deleteRule"
@apply="applyRule"
></AbEditRule>
></ab-edit-rule>
</div>
</template>