# 项目开发指南(Vue 3 + Vite + Element Plus + Axios) > 本文档面向日常开发与维护,覆盖环境准备、目录结构、编码规范、网络请求、UI 使用、构建部署与常见问题等。 ## 一、项目概览 - 框架:Vue 3(Composition API) - 构建:Vite 5 - 组件库:Element Plus - 网络:Axios(已内置实例与拦截器) - 运行脚本:`npm run dev | build | preview` ## 二、环境要求 - Node.js:建议 18+(可用 `node -v` 检查) - 包管理器:npm(内置于 Node)或 pnpm/yarn(任选其一) - 操作系统:Windows / macOS / Linux ## 三、目录结构 当前主要目录: ``` ├─ index.html # 应用入口 HTML ├─ vite.config.js # Vite 配置 ├─ package.json # 脚本与依赖 ├─ src/ │ ├─ main.js # 应用入口,注册 Element Plus │ ├─ App.vue # 示例页面(按钮 + 请求演示) │ └─ plugins/ │ └─ http.js # Axios 实例与拦截器 └─ docs/ └─ 开发指南.md # 本文档 ``` 推荐扩展(按需新增): ``` src/ ├─ api/ # 接口定义与请求函数(封装到 http 实例上) ├─ assets/ # 静态资源(图片、字体等) ├─ components/ # 通用基础组件 ├─ views/ # 页面级组件 ├─ router/ # 路由(如使用 Vue Router) ├─ store/ # 状态管理(如使用 Pinia) ├─ styles/ # 全局样式、变量、主题定制 └─ utils/ # 工具方法(格式化、校验、下载等) ``` ## 四、快速开始 - 安装依赖:`npm install` - 启动开发:`npm run dev`(默认 http://localhost:5173) - 构建产物:`npm run build`(输出至 `dist/`) - 本地预览:`npm run preview` ## 五、配置说明 ### 1. 环境变量 建议使用 Vite 的环境文件管理不同环境: - `.env.development`(开发) - `.env.production`(生产) 示例内容: ``` # .env.development VITE_API_BASE=https://dev-api.example.com # .env.production VITE_API_BASE=https://api.example.com ``` 在代码中使用: ```js const baseURL = import.meta.env.VITE_API_BASE ``` ### 2. Vite 配置(`vite.config.js`) 常用配置要点: - 别名:为 `src` 设置 `@` 方便导入。 - 代理:开发阶段转发 API,避免 CORS。 示例(按需修改后替换到 `vite.config.js`): ```js import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import path from 'node:path' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': path.resolve(__dirname, 'src') }, }, server: { proxy: { '/api': { target: 'https://dev-api.example.com', changeOrigin: true, rewrite: (p) => p.replace(/^\/api/, ''), }, }, }, }) ``` ### 3. Axios 配置(`src/plugins/http.js`) 当前实现: - `baseURL: '/'`(建议改为 `import.meta.env.VITE_API_BASE`) - 超时 15s - 预留请求拦截器(注入 Token)与响应拦截器(统一错误处理) 建议修改: ```js const http = axios.create({ baseURL: import.meta.env.VITE_API_BASE || '/', timeout: 15000, }) ``` 统一错误处理示例(可在响应拦截器中加入): ```js import { ElMessage } from 'element-plus' http.interceptors.response.use( (res) => res, (error) => { const msg = error?.response?.data?.message || error.message || '请求失败' ElMessage.error(msg) return Promise.reject(error) } ) ``` ## 六、代码与组件规范 - 组件目录:一个组件一个目录(可含 `index.vue` / `index.ts`)。 - 命名规范: - 组件名:`PascalCase`(如 `UserCard.vue`)。 - 变量/函数:`camelCase`。 - 文件:`kebab-case`(工具类/样式)。 - 组件结构:`