1、项目路径下,引入axios、qs依赖
npm install axios
npm install qs
2、在项目的src路径下新建一个commJs文件夹,在commJs文件夹里新建aps.js和request.js,api.js用于写接口,对axios的封装写在request.js里
request.js
import axios from 'axios'; import QS from 'qs'; //自动切换环境 axios.defaults.baseURL = process.env._BASEURL //设置超时时间 axios.defaults.timeout = 10000; // post请求头 axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8' axios.defaults.withcredentials = true //请求拦截(请求发出前处理请求) axios.interceptors.request.use((config) => { //在发送请求之前如果为post序列化请求参数 if (config.method === 'post') { config.data = config.data; } return config; }, (error) => { return Promise.reject(error); }); // 响应拦截器(处理响应数据) axios.interceptors.response.use((res) => { //对响应数据做判断,与后台协议统一接口返回格式 console.log('>>>>>>>response: ', res); if (res.data.succ != 'ok') { //这个判断可根据实际情况修改 return Promise.reject(res); } return res; }, (error) => { return Promise.reject(error); }); // 封装get方法 function get(url, params){ return new Promise((resolve, reject) =>{ axios.get(url, params).then(res =>{ resolve(res.data); }).catch(err =>{ reject(err.data); }) }); } // 封装post方法 function post(url, params){ return new Promise((resolve, reject) =>{ axios.post(url, params).then(res =>{ resolve(res.data); }).catch(err =>{ reject(err.data); }) }); } //对外接口 export function request({method, url, data}){ if(method == 'get'){ return get(url, data); }else if(method == 'post'){ return post(url, data); } } export default { install(Vue) { Vue.prototype.$axios = axios; Vue.prototype.$request = function () { return request; } } }
api.js
import {
request
} from './request'
// 列表查询接口
export const getList = (parmas) => {
return request({
url: 'xxx/xxx/xxx',
method: 'post',
data: parmas
})
}
3、在具体组件调用
//index.vue import { getList } from "../../comm/js/api.js"; export default { methods: { getPage() { var param = { currentUser: '', currentPage: "1", pageSize: "10" }; getList(param).then(res => { if (!res.result.list) { this.list = []; } else { this.list = res.result.list; } }); } }