默認vue項目中已經安裝axios,基於element-ui開發,主要記錄配置的相關。vue
axiosConfig.js
import Vue from 'vue' import axios from 'axios' import qs from 'qs' import { Message, Loading } from 'element-ui' // 響應時間 axios.defaults.timeout = 5 * 1000 // 配置cookie // axios.defaults.withCredentials = true // 配置請求頭 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8' // 靜態資源 Vue.prototype.$static = '' // 配置接口地址 axios.defaults.baseURL = '' var loadingInstance // POST傳參序列化(添加請求攔截器) axios.interceptors.request.use( config => { loadingInstance = Loading.service({ lock: true, text: '數據加載中,請稍後...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' }) if (config.method === 'post') { config.data = qs.stringify(config.data) } return config }, err => { loadingInstance.close() Message.error('請求錯誤') return Promise.reject(err) } ) // 返回狀態判斷(添加響應攔截器) axios.interceptors.response.use( res => { if (res.data.code === 200) { loadingInstance.close() return res } else { loadingInstance.close() Message.error(res.data.msg) } }, err => { loadingInstance.close() Message.error('請求失敗,請稍後再試') return Promise.reject(err) } ) // 發送請求 export function fetchPost (url, params) { return new Promise((resolve, reject) => { axios .post(url, params) .then( res => { resolve(res.data) }, err => { reject(err.data) } ) .catch(err => { reject(err.data) }) }) } export function fetchGet (url, params) { return new Promise((resolve, reject) => { axios .get(url, { params: params }) .then(res => { resolve(res.data) }) .catch(err => { reject(err.data) }) }) }
main.js 配置
import { fetchGet, fetchPost} from './api/axiosConfig' Vue.prototype.$get = fetchGet Vue.prototype.$post = fetchPost
組件內部的調用
getData () { let params = { userId: this.userId } this.$get('/xxx', params).then(res => { this.listsData = res.data }).catch(() => { }) }