vue3项目技术点笔记
1 环境变量 - 不同环境用不同的配置
环境变量命名:.env.produciton .env.development
Vite.config.ts 配置 envDir:‘’
链接: VUE3+Vite 环境变量配置
2 axios的封装 http请求拦截,响应拦截。
src下建立公共文件夹Utils下建立request.ts
import axios from 'axios';
// src/global.d.ts
import {
AxiosInstance } from 'axios';
declare module 'vue' {
interface ComponentCustomProperties {
$http: AxiosInstance; // 声明全局属性 $http 的类型
}
}
// 创建 axios 实例
const request = axios.create({
baseURL: import.meta.env.VITE_API_URL, // 设置基础 URL
timeout: 5000, // 请求超时时间
});
// 请求拦截器
request.interceptors.request.use(
(config) => {
// 在发送请求之前做一些处理,比如添加 token
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${
token}`;
config.headers['Content-Type']='application/json';//设备请求头
}
return config;
},
(error) => {
// 处理请求错误
return Promise.reject(error);
}
);
// 响应拦截器
request.interceptors.response.use(
(response