简单的vue axios 封装

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhai_15733218875/article/details/81939563

这里写图片描述
首先 在src里面创建config目录

这是api.url.js里面的代码,根据自己项目需求定义
这里写图片描述

下面 重点来了

import axios from 'axios'
import qs from 'qs'
import apiUrl from '@/config/api.url.js'

// axios 默认配置
axios.defaults.timeout = 5000 // 超时默认设置
axios.defaults.baseURL = apiUrl.baseURL // 默认baseUR
// axios.defaults.responseType = 'json' // 默认数据相应类型
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.withCredentials = true // 表示跨域请求时是否需要使用凭证

export default (url, data = {}, type = 'GET') => {
  url = apiUrl.baseURL + url
  type = type.toUpperCase()

  /*
    get 方法封装
    @param url
    @param data
    @returns {Promise}
  */
  if (type === 'GET') {
    return new Promise((resolve, reject) => {
      axios.get(url, {params: data})
        .then(res => {
          res = res.data
          if (res.code === 200) {
            resolve(res.data)
          } else {
            reject(res.data)
          }
        }, err => {
          console.log(err)
          reject(err)
        })
    })
  }

  /*
    post 方法封装
    @param url
    @param data
    @returns {Promise}
  */
  if (type === 'POST') {
    return new Promise((resolve, reject) => {
      axios.post(url, qs.stringify(data))
        .then(res => {
          res = res.data
          if (res.code === 200) {
            resolve(res.data)
          } else {
            reject(res.data)
          }
        }, err => {
          reject(err)
        })
    })
  }
}

使用如下:
注意我在main.js 有几行代码

import http from '@/config/index.js' // axios二次封装配置
import apiUrl from '@/config/api.url.js' // 各种url暴露
Vue.prototype.$http = http
getTableList (limit, page) {
      this.stop && clearTimeout(this.stop)
      this.$http('/get-user-list', {
        'limit': limit,
        'page': page
      }, 'get')
        .then((res) => {
          this.loading = false
          this.pagination.pageCount = res.count
          this.pagination.limit = this.pagination.limit
          this.info = res.list
        })
        .catch((error) => {
          this.loading = false
          this.errorLoading = true
          this.$message.error('获取失败!')
          console.warn(error)
        })
    }

猜你喜欢

转载自blog.csdn.net/zhai_15733218875/article/details/81939563