前言:

在写前端项目的时候我们一般都是在当前vue界面中去填写后端请求地址,去进行请求数据,这样的话如果我们需要改变一个接口的请求地址那么所以引用过这个地址的都需要进行改动。

比较繁琐和不便于管理,如果我们把后端的请求接口进行统一管理,那么是不是会好很多呢。

定义环境配置

环境配置的主要目的是在启动项目或者打包项目的时候给定一个全局的变量

vite官网环境变量文档vue cli官网环境变量文档

我们这里主要是介绍vite至于vue cli也是差不多一样的,看一下文档就知道了。

创建.env文件

.env相当于环境文件(具体去看文档)

在项目根目录创建.env.dev.env.prod分别用于本地和线上环境

  • .env.dev

    1
    2
    3
    VITE_BASE_URL=https://localhost:7100/his-api
    VITE_BASE_MINIO_URL=http://localhost:9000/his
    VITE_ENV=dev
  • .env.prod

    1
    2
    3
    VITE_BASE_URL=https://www.staro.cc/his-api
    VITE_BASE_MINIO_URL=http://www.staro.cc/his/minio
    VITE_ENV=prod

启动配置

packpage.json启动的时候我们需要指定对应的环境配置文件 --mode 指定文件

1
2
3
4
5
6
"scripts": {
"dev": "vite dev --mode dev",
"dev-prod": "vite dev --mode prod",
"build": "vue-tsc && vite build --mode prod",
"preview": "vite preview"
}

封装请求方法

  • src/global/request.ts编写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import router from '../router';
//导入JQuery库,因为Ajax用起来非常方便,支持同步和异步的Ajax请求
// @ts-ignore
import $ from 'jquery';

//导入ElementUI的消息通知组件,下面封装全局Ajax的时候处理异常的时候需要弹出通知
import {ElMessage} from 'element-plus';
import {App} from "vue";

//后端项目的URL根路径
let $baseUrl = import.meta.env.VITE_BASE_URL;

//Minio服务器地址
let $minioUrl = import.meta.env.VITE_BASE_MINIO_URL;
//封装全局Ajax公共函数
export const $http = function (url: string, method: string, data: JSON, async: boolean, fun: Function) {
$.ajax({
url: $baseUrl + url,
type: method,
dataType: 'json',
contentType: 'application/json',
//上传的数据被序列化(允许Ajax上传数组)
traditional: true,
xhrFields: {
//允许Ajax请求跨域
withCredentials: true
},
headers: {
token: localStorage.getItem('token')
},
async: async,
data: method == "GET" ? data : JSON.stringify(data),
success: function (resp: any) {
if (resp.code == 200) {
fun(resp);
} else {
ElMessage.error({
message: resp.msg,
duration: 1200
});
}
},
error: function (e: any) {
//ajax有语法错误的时候
if (e.status == undefined) {
ElMessage.error({
message: '前端页面错误',
duration: 1200
});
} else {
let status = e.status;
if (status == 401) {
if (url.startsWith('/front/')) {
router.push({
name: 'FrontIndex'
});
} else {
router.push({
name: 'Login'
});
}
} else {
//后端没有运行,提交的数据有误,或者没有连接上后端项目
if (!e.hasOwnProperty('responseText')) {
ElMessage.error({
message: '后端项目没有启动,或者HTTP请求类型以及参数错误',
duration: 1200
});
} else {
ElMessage.error({
message: e.responseText,
duration: 1200
});
}
}
}
}
});
};
// 基于Http进行再封装 POST
const $post = (url: string, data: JSON, fun: Function, async: boolean = true) => {
// 默认异步,true 是异步 false是同步
$http(url, "POST", data, async, fun);
}
// 基于Http进行再封装 GET
const $get = (url: string, data: JSON, fun: Function, async: boolean = true) => {
// 默认异步,true 是异步 false是同步
$http(url, "GET", data, async, fun);
}
// 全局接口 统一管理 还未定义,看下面
import api from './api';

export default {
//挂载到全局
install(app: App) {
app.config.globalProperties['$http'] = $http;
app.config.globalProperties['$post'] = $post;
app.config.globalProperties['$get'] = $get;
app.config.globalProperties['$minioUrl'] = $minioUrl;
app.config.globalProperties['$baseUrl'] = $baseUrl;
app.config.globalProperties['$api'] = api;
}
}

定义api

src/global/api.ts编写

1
2
3
export default ({
login: '/user/login',//登录
})

main.ts进行引入

1
2
3
4
5
import request from "./global/request.ts";
const app = createApp(App);
// 请求相关函数
app.use(request)
app.mount('#app');

这样就完成了。

引用api

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import {getCurrentInstance, reactive, ref} from 'vue';
proxy.$post(proxy.$api.login, data, (resp: any) => {
if (resp.result) {
const token = resp.token;
localStorage.setItem('token', token);
// 跳转页面
router.push({name: 'home'})
} else {
proxy.$message({
message: '登录失败',
type: 'error',
duration: 1200
})
}
})

还可以在进行很大的改动,如果有好的想法记得分享。