法一
http 封装
使用 ky 库
// utils/ http.js
import ky from 'ky'
const http = {}
const LEGACY_URL_REGEXP = /^\/api\//
function createRequest(method) { // 创建请求
return async (url, options) => {
if (process.env.NODE_ENV !== 'production' && (!url || !/^\//.test(url))) {
logger.warn('地址要以/开头')
throw new Error('地址要以/开头')
}
let SUCCESS_CODE = 0
if (LEGACY_URL_REGEXP.test(url)) {
SUCCESS_CODE = 1
}
try {
const resp = await ky[method](url, options).json()
if (resp && resp.code !== SUCCESS_CODE) {
toast.danger(resp.message || resp.msg, url)
return Promise.reject(resp)
}
return resp
} catch (error) {
const url = error?.response?.url
toast.danger(error.message, url)
throw error
}
}
}
function wrapper(fn, enhance) { // 解耦
return enhance(fn)
}
// 封装 get
http.get = wrapper(createRequest('get'), (fn) => (url, options) => {
const { query, searchParams, ...others } = options || {}
return fn(url, {
...others,
// 对象或者URLSearchParams都会自动转化为 URLSearchParams对象
searchParams: searchParams || query,
})
})
export { http }
api 封装
// src/apis/activity.js
import { http } from '@/utils/http'
const URLS = {
AWARD_CONF_LIST: 'xxx',
}
export function getAwardList(searchParams) {
return http.get(URLS.AWARD_CONF_LIST, { searchParams })
}
组件内使用
import * as api from '@/apis/activity'
async function getList({ query }) {
try {
const { data } = await api.getAwardList({
...query,
activity_id: act.value.actId,
ps: 20,
})
const { list, page, size, total } = data
}catch (err){
console.error(err)
}
}
法二
由 then 接收成功请求,中间多一层统一处理 数据 和 异常
使用 axios-rest-client
库,做事件封装
service
import axiosRestClient from "axios-rest-client"
const service = axiosRestClient({
baseUrl: "http://localhost:3002/api", // this is required
})
service.endpoints({
prize: "prize"
})
// api.json.all() // GET /users
// api.json.find(1) // Get /users/1
// api.json.create(data) // POST /users, body=data
// api.json.update(1, data) // PUT /users/1, body=data
// api.json.delete(1) // DELETE /users/1
export { service }
request
import { service } from '@/util/service'
function prizeRequest () {
return new Promise((resolve, reject) => {
service.prize.all().then((res: any) => {
// 这里处理数据
resolve(res.data.prizeList)
}).catch((err: any) => {
// 这里处理异常
console.error('prizeRequest',err)
reject(err)
})
})
}
export { prizeRequest }
组件内使用
import { prizeRequest } from "@/util/request"
onBeforeMount(() => {
// 请求奖品列表
prizeRequest().then((res:any) => {
prizeList.push(...res)
console.log(prizeList, "onMounted")
})
})