項目中
axios
和
api
已分别封裝在
http.js
和
api.js
裡面,代碼demo如下:
tips:
1、實作是否需要loading,在請求方法裡面添加config參數配置,并在請求攔截器裡判斷showLoading,決定是否執行loading元件
2、實作多個請求合并一個loading,檢視http.js裡
// 加載函數Loading S
=>
// 加載函數Loading E
http.js
import Vue from 'vue'
import axios from 'axios'
var instance = axios.create({
// baseURL: '/api',
baseURL: process.env.API_ROOT,
timeout: 30 * 1000
})
instance.defaults.headers.common['Authorization'] = 'AUTH_TOKEN'
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 添加請求攔截器
instance.interceptors.request.use(function (config) {
// 在發送請求之前做些什麼
/* 添加loading S */
if (config.config.showLoading === true) {
showLoading()
}
/* 添加loading E */
return config
}, function (error) {
// 對請求錯誤做些什麼
/* 關閉loading S */
hideLoading()
/* 關閉loading E */
return Promise.reject(error)
})
// 添加響應攔截器
instance.interceptors.response.use(function (response) {
// 對響應資料做點什麼
/* 關閉loading S */
hideLoading()
/* 關閉loading E */
return response
}, function (error) {
// 對響應錯誤做點什麼
/* 關閉loading S */
hideLoading()
/* 關閉loading E */
// 請求逾時處理
if (error.message.indexOf('timeout') !== -1) {
alert('請求逾時,請重新重新整理頁面!')
}
return Promise.reject(error)
})
// 加載函數Loading S
let loading
let needLoadingRequestCount = 0
function showLoading () {
if (needLoadingRequestCount === 0) {
startLoading()
}
needLoadingRequestCount++
}
function hideLoading () {
setTimeout(tryCloseLoading, 300)
}
function tryCloseLoading () {
if (needLoadingRequestCount <= 0) return
needLoadingRequestCount--
if (needLoadingRequestCount === 0) {
endLoading()
}
}
function startLoading () {
loading = Vue.prototype.$loading({
lock: true,
text: '加載中……',
background: 'rgba(0, 0, 0, .5)',
target: document.querySelector('.loading-g') // 設定加載動畫區域
})
}
function endLoading () {
Vue.nextTick(function () {
// DOM 更新了
loading.close()
})
}
// 加載函數Loading E
var HttpRequest = {
// get請求
get (url, params, config = { showLoading: true }) {
return new Promise((resolve, reject) => {
instance({
method: 'get',
url: url,
params: params,
config: config
}).then(response => {
// 請求成功
resolve(response.data)
}).catch(err => {
// 請求失敗
console.log('請求失敗')
reject(err)
})
})
},
// post請求
post (url, data, config = { showLoading: true }) {
return new Promise((resolve, reject) => {
instance({
method: 'post',
url: url,
data: data,
config: config
}).then(response => {
// 請求成功
resolve(response.data)
}).catch(err => {
// 請求失敗
console.log('請求失敗')
reject(err)
})
})
}
}
export default HttpRequest
api.js
import HttpRequest from './http'
export default {
/* User api Start */
// 接口 登入
pLogin: p => HttpRequest.post('/User/Login', p),
// 接口 登入 - 圖檔驗證碼
pLoginCode: (p, showLoading) => HttpRequest.get('/User/captcha', p, showLoading)
}