1. 程式人生 > >vue簡單封裝axios

vue簡單封裝axios

1、在src下新建api資料夾,在api資料夾下新建config.js檔案

2、config.js配置如下:

import axios from 'axios';
import qs from 'qs'

//mint UI 框架,若不需要請全部註釋掉
import {Indicator, Toast} from 'mint-ui'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

axios.defaults.baseURL = 'http://testweb.fishing.tianenfishing.cn/fishweb';

// 新增請求攔截器
axios.interceptors.request.use(config => {
  Indicator.open({
    text: '載入中...',
    spinnerType: 'fading-circle'
  })
  return config
},
err => {
  Indicator.close()
  Toast({
    message: '載入超時',
    position: 'middle',
    duration: 3000
  })
  return Promise.reject(err)
})
 
// 新增響應攔截器,響應攔截器會在then/catch處理之前執行
axios.interceptors.response.use(response => {
  let timetp = null
  clearTimeout(timetp)
  timetp = setTimeout(() => {
    Indicator.close()
    clearTimeout(timetp)
  }, 500)
  // 只將請求結果的data欄位返回 
  return response.data
},
error => {
  return Promise.reject(error);
  // 發生網路錯誤後會走到這裡
  // promise.resolve("ssss")
})

//返回一個Promise
export function fetch(url, params,type) {
  return new Promise((resolve, reject) => {
    if(type=='post'){
      axios.post(url, qs.stringify(params))
      .then(response => {
          resolve(response.data);
      }, err => {
          reject(err);
      })
      .catch((error) => {
          reject(error)
      })
    } else{
      axios.get(url,{params})
      .then(response => {
          resolve(response.data);
      }, err => {
        reject(err);
      })
      .catch((error) => {
          reject(error)
      })
    }   
  })
}

3、在api資料夾下新建api.js

4、引入config.js

import {fetch} from './config'
export default {
    bindAccount (params) {return fetch(`user/bind`, params, 'post')}
}

5、頁面請求需引入api

<script>
import api from '@/api/api';
export default {
    methods: {
        let params = {
        name: this.name,
        mobile: this.phone,
        code: this.code
      }
      api.bindAccount(params).then((res) => {
        console.log(res)
      }).catch((error) => {
        console.log(error)
      })
    }
}
</script>