mirror of
https://github.com/EstrellaXD/Auto_Bangumi.git
synced 2026-04-01 09:40:59 +08:00
hook: useApi
This commit is contained in:
51
src/hooks/useApi.ts
Normal file
51
src/hooks/useApi.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user