项目约定
本文档介绍项目开发中的约定和规范。
命名规范
文件命名
- 组件文件:大驼峰命名,如
UserList.vue - 工具文件:小驼峰命名,如
formatDate.ts - 常量文件:全小写,如
constants.ts - 类型文件:大驼峰命名,如
UserType.ts
变量命名
typescript
// 常量:全大写下划线
const API_BASE_URL = 'https://api.example.com';
// 变量:小驼峰
const userName = 'admin';
// 函数:小驼峰,动词开头
function getUserInfo() {}
// 类:大驼峰
class UserService {}
// 接口:大驼峰,I 开头
interface IUserInfo {}
// 类型:大驼峰
type UserType = {};目录结构
src/
├── api/ # API 接口
├── assets/ # 静态资源
├── components/ # 公共组件
├── composables/ # 组合式函数
├── hooks/ # Hooks
├── layouts/ # 布局
├── router/ # 路由
├── store/ # 状态管理
├── styles/ # 样式
├── types/ # 类型定义
├── utils/ # 工具函数
└── views/ # 页面代码组织
组件结构
vue
<script setup lang="ts">
// 1. 导入
import { ref } from 'vue';
// 2. 类型定义
interface Props {
title: string;
}
// 3. Props 和 Emits
const props = defineProps<Props>();
const emit = defineEmits<{
change: [value: string];
}>();
// 4. 响应式数据
const count = ref(0);
// 5. 计算属性
const doubleCount = computed(() => count.value * 2);
// 6. 方法
function increment() {
count.value++;
}
// 7. 生命周期
onMounted(() => {
console.log('mounted');
});
</script>
<template>
<!-- 模板 -->
</template>
<style scoped>
/* 样式 -->
</style>API 接口
接口定义
typescript
// src/api/user.ts
import { request } from '@/utils/http';
export interface UserInfo {
id: string;
username: string;
email: string;
}
export function getUserListApi(params: any) {
return request.get<UserInfo[]>('/user/list', { params });
}
export function createUserApi(data: UserInfo) {
return request.post('/user/create', data);
}类型定义
类型文件
typescript
// src/types/user.ts
export interface UserInfo {
id: string;
username: string;
email: string;
phone?: string;
}
export type UserStatus = 'active' | 'inactive' | 'banned';
export enum UserRole {
ADMIN = 'admin',
USER = 'user',
GUEST = 'guest'
}注释规范
函数注释
typescript
/**
* 获取用户信息
* @param userId 用户 ID
* @returns 用户信息
*/
export function getUserInfo(userId: string): Promise<UserInfo> {
return request.get(`/user/${userId}`);
}组件注释
vue
<script setup lang="ts">
/**
* 用户列表组件
*
* @example
* <UserList :data="users" @change="handleChange" />
*/
</script>Git 提交规范
提交格式
<type>(<scope>): <subject>
<body>
<footer>类型说明
feat:新功能fix:修复 bugdocs:文档更新style:代码格式refactor:重构test:测试chore:构建/工具
示例
feat(user): 添加用户列表页面
- 实现用户列表查询
- 添加分页功能
- 支持搜索和筛选
Closes #123错误处理
统一错误处理
typescript
try {
const result = await getUserInfo(userId);
// 处理成功
} catch (error) {
// 统一错误处理
message.error(error.message);
}性能优化
组件懒加载
typescript
const UserList = defineAsyncComponent(() =>
import('@/views/user/UserList.vue')
);图片懒加载
vue
<template>
<img v-lazy="imageUrl" alt="image" />
</template>安全规范
- XSS 防护:使用
v-text而不是v-html - CSRF 防护:请求携带 token
- 敏感信息:不在前端存储敏感信息
- 权限控制:前后端都要做权限验证