项目 api 封装(vue版)

法一

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")
      })
    })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值