vue 封装Axios请求

本文介绍了在Vue项目中如何封装axios以简化代码和提高效率。通过创建http.js文件封装get和post方法及拦截器,然后在roleApi.js中针对不同请求进行封装,最后在业务模块直接导入并使用,使得在role.vue中只需一行代码即可完成请求操作。

在做 vue 的项目中,获取后端数据使用 axios ,使用的地方可以说是很多了,我写代码总喜欢整整齐齐的,所以,对 axios 请求进行了封装,方便使用,减少了不少的冗余代码呢~

目录情况如下:

|-------src

| |-- api

| | |-- http.js

| | |-- roleApi.js

| |-- views

| | |-- role.vue

(1)首先,封装 axios 的 get、post方法、请求拦截(请求发出前处理请求)和响应拦截器(处理请求响应后的数据),新建文件 http.js:

import axios from 'axios'
import { Message } from 'element-ui'

// create an axios instance
const http = axios.create({
  baseURL: '后端接口地址',
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000
  // request timeout
})

// 设置 post、put 默认 Content-Type
http.defaults.headers.post['Content-Type'] = 'application/json'
http.defaults.headers.put['Content-Type'] = 'application/json'

// request interceptor 请求拦截(请求发出前处理请求)
http.interceptors.request.use(
  config => {
    // do something before request is sent
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor 响应拦截器(处理响应数据)
http.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    const ressuc = res.success
    // 后端返回成功失败是用 success 的true 和 false 判断,所以在这里就获取 response.data 的 success 
    if (ressuc) {
      console.log('response', response)
      return res
    } else {
      Message({
        message: res.message || 'error',
        type: 'error',
        duration: 5 * 1000
      })
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 封装get方法
export function get({ url, params }) {
  return new Promise((resolve, reject) => {
    http.get(url, {
      params: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

// 封装post方法
export function post({ url, data }) {
  return new Promise((resolve, reject) => {
    http.post(url, data).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

(2)接下来,对不同的请求进行封装,新建文件 roleApi.js:

import { get, post } from './http' // 导入axios实例文件中方法

const server = {
  //带参数的 get 方法
  getById(param) {
    return get({
      url: '/role/getById',
      method: 'get',
      params: param
    })
  }
  //不带参数的 get 方法
  getAll() {
    return get({
      url: '/role/getAll',
      method: 'get'
    })
  },
  // post 方法
  save(param) {
    return post({
      url: '/role/save',
      method: 'post',
      data: param
    })
  }
}

export default server

(3)最后,就是在业务模块直接导入 api 文件,role.vue 文件中使用:

import apis from '@/api/roleApi'
// 用try catch包裹,请求失败的时候就执行catch里的代码
try {
     const param = {
          id: 'admin'
     }             
     const res = await apis.getById(param)
     console.log('getById:', res)
} catch (e) {
      //提示错误
      console.log(e)
} 

用这种方式,使用 axios 时只需要一句简单的代码既可以得到返回结果,可以说是很方便啦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值