官方文档地址​​axios​安装axios

npm install axios

在main.js中添加

import Axios from 'axios'
Vue.prototype.$axios = Axios;

new Vue({
el: '#app',
Axios,
components: { App },
template: '<App/>'
})

在src中新建一个axios文件夹,建一个http.js文件
Dialog为vant组件

import axios from "axios";
import qs from "qs";
import {
Dialog
} from "vant";

// 读取环境配置获取接口地址
axios.defaults.baseURL = process.env.VUE_APP_BASE_URL;

//post请求头
axios.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded;charset=UTF-8";
//设置超时
axios.defaults.timeout = 10000;

axios.interceptors.request.use(
config => {
return config;
},
error => {
return Promise.reject(error);
}
);

axios.interceptors.response.use(
response => {
if (response.status == 200) {
return Promise.resolve(response);
} else {
return Promise.reject(response);
}
},
error => {
Dialog.alert({
title: '提示',
message: '网络请求失败,请刷新重试',
})
}
);

export default {
post(url, data) {
return new Promise((resolve, reject) => {
axios({
method: 'post',
url,
data: qs.stringify(data),
})
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err)
});
})
},

get(url, data) {
return new Promise((resolve, reject) => {
axios({
method: 'get',
url,
params: data,
})
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err)
})
})
}
};

在main.js中引入

import https from './axios/http'
Vue.prototype.https =

新建个request.js文件用来放全部接口

import http from './http'

//Object.assign拷贝每个接口固定传参
const post = (url, data) => http.post(url, Object.assign({
api_key: "133132",
sign: "133132"
}, data))


/**
* 传一个参数的
* @param {*}
*/
const getClassSchedule = (schedule_id) => post('getClassSchedule', {
schedule_id,
})

/**
* 传多个参数的
* @param {*}
* page:1
* limit:10 最大页数
*/
const getCarouselList = ({
page,
limit
}) => post('getCarouselList', {
page,
limit,
})

/***
* 不传参数的
* @param {*}
*/
const getUserInfo = () => post('getUserInfo', {})

//接口导出
export {
getClassSchedule,
getCarouselList,
getUserInfo
}

在组件中调用

//导入接口
import { getClassSchedule ,getCarouselList,} from "../axios/request";
export default {

methods: {
//传一个值的
async getmore() {
const res = await getClassSchedule(id);
if (res.status == 1) {
} else {
}
},
//传多个值的
async getbanner() {
const res = await getCarouselList({ page: 1, limit: 10 });
if (res.status == 1) {
} else {
}
}
//不传值的
async getinfo() {
const res = await getUserInfo();
if (res.status == 1) {
} else {
}
},
}
}