一、配置一个默认地址
1.在src下创建api文件夹
2.在api里创建config.js 和 index.js文件
3.在config.js里引入axios,写入以下内容
import axios from 'axios';
const http = axios.create({
baseURL: 'xxxxxxxxxx', //配置默认地址
timeout: 1000 * 100,
});
export default http;
4.在index.js里导入config.js里的http,把他取别名axios(可以不起别名,就导入http)
5.在需要的地方引入index文件,然后调用接口(我这里是把index文件取名为api)
二、配置多个默认地址
方式一、
- 在api文件夹中新建两个文件
config.js
和index.js
- 在
config.js
文件中配置默认地址,然后导出http和sec两个变量 - 在
index.js
文件中使用解构导入变量 - 在需要使用接口的文件内导入index.js文件 并使用接口
import * as api from "../../api/index"
api.getPopulation()
.then(res=> {
console.log(res)
})
api.getDriverNum()
.then(res=> {
console.log(res)
})
方式二、
- 新建文件
index.js
、config.js
、otherUrl.js
- 在
config.js和otherUrl.js
文件分别配置默认地址,并导出 - 在index.js文件里分别导入两个文件
- 在需要使用接口的文件内导入index.js文件 并使用接口
三、关于 import * as
import * as api from '../../xxx' 代表一次性全部导入xxx文件中所有的变量
参考文章
(1)Vue项目中的接口调用