//axios.js文件
export default {
request(url,data={},options={loading:true,mock:false}){
let loading = document.getElementById('ajaxLoading');
if (options.loading){
loading.style.display = 'block';
}
let baseApi = '/api';
//局部mock
if(options.mock){
// 一、直接加载mock文件
require('./mock/api');
// 二、对接easy-mock
baseApi = 'https://www.easy-mock.com/mock/5dc7afee2b69d9223b633cbb/mimall'
}
return new Promise((resolve,reject)=>{
axios({
url:url,
method:options.method || 'get',
baseURL:baseApi,
timeout:options.timeout || 5000,
params: data
}).then((response)=>{
if (options.loading) {
loading.style.display = 'none';
}
if (response.status == '200'){
let res = response.data;
if (res.code == '0'){
resolve(res.data);
}else{
Message.error(res.msg);
}
}else{
reject(response.data);
}
}).catch(()=>{
loading.style.display = 'none';
})
});
}
}
//用法
import Axios from 'util/axios'
Axios.request('/products',{
categoryId:100012,
pageSize:14
},{ mock:true }).then((res)=>{
//to-do...
})
//或者直接挂载到Vue原型上
Vue.prototype.$request = Axios.request
this.$request('/products',{
categoryId:100012,
pageSize:14
},{ mock:true }).then(()=>{
//to-do...
})