本文主要是介绍Vue+iView LoadingBar封装Axios请求,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import Axios from 'axios'
import qs from 'qs'
import iView from 'iview'Axios.defaults.timeout = 60000
Axios.defaults.baseURL = ''//http request 拦截器
Axios.interceptors.request.use(config => {if(config.method === 'post') {config.data = qs.stringify(config.data); config.headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}} else if(config.method === 'get') {let newParams = {}for(let key in config.params) {newParams[key] = encodeURIComponent(config.params[key])}config.params = newParamsconfig.headers = {'Content-Type': 'application/json;charset=UTF-8'}}//开始显示LoadingBariView.LoadingBar.start();return config},error => {//失败显示LoadingBariView.LoadingBar.error();return Promise.reject(error)}
)//http response 拦截器
Axios.interceptors.response.use(response => {let data = response.dataif(data.successFlag === 1) {//关闭显示LoadingBariView.LoadingBar.finish();return Promise.resolve(data)} else {iView.LoadingBar.error();return Promise.reject(data)}},error => {iView.LoadingBar.error();return Promise.reject(error)}
)/*** 封装get方法* @param url* @param data* @returns {Promise}*/const get = function get(url, params = {}) {return new Promise((resolve, reject) => {Axios.get(url, {params: params}).then(response => {resolve(response);}).catch(err => {reject(err)})})
}/*** 封装post请求* @param url* @param params* @returns {Promise}*/const post = function post(url, params = {}) {return new Promise((resolve, reject) => {Axios.post(url, params).then(response => {resolve(response);}, err => {reject(err)})})
}/*** 封装patch请求* @param url* @param data* @returns {Promise}*/const patch = function patch(url, data = {}) {return new Promise((resolve, reject) => {Axios.patch(url, data).then(response => {resolve(response);}, err => {reject(err)})})
}/*** 封装put请求* @param url* @param data* @returns {Promise}*/const put = function put(url, data = {}) {return new Promise((resolve, reject) => {Axios.put(url, data).then(response => {resolve(response);}, err => {reject(err)})})
}export default {post,get,patch,put
}
这篇关于Vue+iView LoadingBar封装Axios请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!