Skip to content

Commit

Permalink
feat: 请求示例加上自动请求示例
Browse files Browse the repository at this point in the history
  • Loading branch information
yuntian001 committed Nov 7, 2022
1 parent e950419 commit f5e739b
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 23 deletions.
2 changes: 1 addition & 1 deletion mock/apiDemo/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default [
total: 30,
list,
},
'登录成功',
'操作成功',
);
},
},
Expand Down
19 changes: 10 additions & 9 deletions src/api/example.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import request from '@/utils/request';

import { request, RequestOptions } from '@/utils/request';
const enum Api {
LIST = '/api/list',
INFO = '/api/list/info/',
Expand All @@ -14,14 +13,16 @@ export interface ListResult {
total: number;
list: string[];
}
export function listApi() {
return request<ListResult, [ListParams]>((params) => ({
url: Api.LIST,
method: 'get',
params,
}));
export function listApi(options: RequestOptions<ListResult, [ListParams]>) {
return request(
(params) => ({
url: Api.LIST,
method: 'get',
params,
}),
options,
);
}

export function infoApi() {
return request<string, [number]>((id) => ({
url: Api.INFO + id,
Expand Down
21 changes: 11 additions & 10 deletions src/utils/request.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { closeLoading, loading } from '@/utils/loading';
import { useUserStore,useGlobalStore } from '@/store';
import { useUserStore, useGlobalStore } from '@/store';
import axios, { AxiosRequestConfig } from 'axios';
import { ElMessage } from 'element-plus';
import log from './log';
import { useRequest, Options, setGlobalOptions } from 'vue-request';
const t = (...args:[string|number])=>useGlobalStore().i18n.t(...args);
const t = (...args: [string | number]) => useGlobalStore().i18n.t(...args);
const service = axios.create({
baseURL: '/', // url = base url + request url
timeout: 10000, // request timeout
Expand Down Expand Up @@ -42,7 +42,7 @@ service.interceptors.response.use(
},
);

type RequestOptions<R, P extends unknown[]> = {
export type RequestOptions<R, P extends unknown[]> = {
needAll?: boolean; // 需要所有的格式,而不仅仅是data
noLoading?: boolean; // 不需要加载特效
noError?: boolean; // 不需要错误提示
Expand All @@ -55,12 +55,12 @@ setGlobalOptions({
});

// 请求函数,当请求失败时直接抛出异常;
function request<R, P extends unknown[] = []>(
axiosConfig: (...args: P) => AxiosRequestConfig,
export function request<R, P extends unknown[] = []>(
axiosConfig: (...args: P) => AxiosRequestConfig | Promise<AxiosRequestConfig>,
options?: RequestOptions<R, P>,
): ReturnType<typeof useRequest<R, P>>;
function request<R, P extends unknown[] = [], T extends boolean | undefined = boolean | undefined>(
axiosConfig: (...args: P) => AxiosRequestConfig,
export function request<R, P extends unknown[] = [], T extends boolean | undefined = boolean | undefined>(
axiosConfig: (...args: P) => AxiosRequestConfig | Promise<AxiosRequestConfig>,
options: RequestOptions<R, P>,
returnAxios?: T,
): T extends boolean ? (...args: P) => Promise<R> : ReturnType<typeof useRequest<R, P>>;
Expand All @@ -71,14 +71,15 @@ function request<R, P extends unknown[] = [], T extends boolean | undefined = bo
* @param returnAxios
* @returns
*/
function request<R, P extends unknown[] = [], T = boolean>(
axiosConfig: (...args: P) => AxiosRequestConfig,
export function request<R, P extends unknown[] = [], T = boolean>(
axiosConfig: (...args: P) => AxiosRequestConfig | Promise<AxiosRequestConfig>,
options?: RequestOptions<R, P>,
returnAxios?: T,
) {
const axiosService = async (...args: P): Promise<R> => {
try {
!options?.noLoading && loading();
//loading放到微任务中去执行以确保在自动调用请求时等待所有的宏任务中的生命周期函数执行完再创建loading实例 以规避currentInstance的相关警告
!options?.noLoading && Promise.resolve(undefined).then(loading);
const { data: res } = await service(await axiosConfig(...args));
if (!res || res.code === undefined) {
throw Error(t('返回值解析失败'));
Expand Down
5 changes: 2 additions & 3 deletions src/views/example/request.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<template>
<div class="request">
请求示例 1
<el-button @click="run({ page: 1, size: 2 })">请求</el-button>
<el-button @click="run({ page: 2, size: 2 })">请求</el-button>
<el-button @click="run({ page: 0, size: 10 })">error请求</el-button>
<div>
loading:<code>{{ loading }}</code> error:<code>{{ JSON.stringify(error) }}</code> data:<code>{{
Expand All @@ -19,8 +19,7 @@
</template>
<script setup lang="ts" name="Request">
import { infoApi, listApi } from '@/api/example';
const { run, loading, error, data } = listApi();
const { run, loading, error, data } = listApi({ defaultParams: [{ page: 1, size: 10 }], manual: false });
const { runAsync: runAsync2, loading: loading2, error: error2, data: data2 } = infoApi();
const getInfo = async () => {
console.log(await runAsync2(1));
Expand Down

0 comments on commit f5e739b

Please sign in to comment.