// 对 useFetch的封装 import { UseFetchOptions } from 'nuxt/app' import { BASE_URL } from './config' type IonResponse = ( context: FetchContext & { response: FetchResponse } ) => Promise | void type IonRequest = (context: FetchContext) => void class Request { private baseUrl: string private onRequest?: IonRequest private onResponse?: IonResponse constructor(baseUrl: string, onRequest?: IonRequest, onResponse?: IonResponse) { this.baseUrl = baseUrl this.onRequest = onRequest this.onResponse = onResponse } request(url: string, type: 'get' | 'post', options?: UseFetchOptions) { return new Promise((resolve, reject) => { useFetch(url, { ...options, method: type, baseURL: this.baseUrl, onRequest: this.onRequest, onResponse: this.onResponse }) .then((res) => { resolve(res.data.value as T) }) .catch((err) => { reject(err) }) }) } get(url: string, options: UseFetchOptions) { return this.request(url, 'get', options) } post(url: string, options: UseFetchOptions) { return this.request(url, 'post', options) } } export default new Request(BASE_URL)