axios帶有請求攔截器,避免在每一個請求裏面加loading重複操做,能夠封裝進去,在請求開始時加載loading層,請求結束關閉,loading層用vux的loading加載vue
axios.jsios
import axios from 'axios' import Vue from 'vue' // 超時時間 axios.defaults.timeout = 15000; // axios.defaults.withCredentials=true; // http請求攔截器 axios.interceptors.request.use(config => { Vue.$vux.loading.show({ text: 'Loading' }) return config }, error => { setTimeout(() => { Vue.$vux.loading.hide(); Vue.$vux.toast.text('加載超時', 'middle') },3000) return Promise.reject(error) }) // http響應攔截器 axios.interceptors.response.use(data => {// 響應成功關閉loading Vue.$vux.loading.hide() return data }, error => { setTimeout(() => { Vue.$vux.loading.hide() Vue.$vux.toast.text('請求失敗', 'middle') },1000) return Promise.reject(error) }) export default axios;
封裝get和post方法 axios.service.jsajax
import axios from './axios'; class myAxios{ getUrl(url){ return `${__ce.baseURL}${url}`; // 打包時用這個 __ce.baseURL // return `/api${url}`; // 防止跨域,開發環境用這個代理 }; //公共ajax; postServer(opt) { let data = {}; if (opt.data) { data = opt.data; } axios.post(opt.url, data).then((response) => { console.log(response); if(!response.data.status){ return; } if (opt.onSuccess) { opt.onSuccess(response); } }).catch(error => { if (opt.onFailed) { opt.onFailed(error); } }); } // get 請求 getServer(opt) { let data = {}; if (opt.data) { data = opt.data; } axios.get(opt.url, {params: data}).then((response) => { if (opt.onSuccess) { opt.onSuccess(response); } }).catch(error => { if (opt.onFailed) { opt.onFailed(error); } }); } setData(opt) { let data = {}; if (opt.data) { data = opt.data; } return data; } } export default myAxios;
封裝方法~axios
import myAxios from './axios.service' const myAxiosMethods = new myAxios(); class RecordServer{ // 查詢訂單 -- post方法 sendMiceIndentSearchServer(opt){ const data = myAxiosMethods.setData(opt); const url = myAxiosMethods.getUrl('/search');// 這裏的/search是後端給的接口地址 myAxiosMethods.postServer({url, data, onSuccess: opt.onSuccess, onFailed: opt.onFailed}); } export default RecordServer;
在頁面中使用後端
const recordSever = new RecordServer()
methods:{ _sendSearchServer(){ // 在須要的地方調用這個方法 recordServer.sendSearchServer({ data: this.params, // params是這個接口須要傳遞給後臺的參數 onSuccess: (res) => { console.log(res) }, onFailed: (err) => { console.log(err) } }) } }