vue2-code-style
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese代码风格规范
Code Style Guidelines
何时使用
When to Use
在编写任何代码时都应遵循此规范,确保代码风格一致、可读性强、易于维护。
Follow this guideline whenever writing code to ensure consistent code style, strong readability, and ease of maintenance.
基本原则
Basic Principles
- DRY 原则:保持代码简洁、清晰、可维护,避免重复
- 完整性:代码必须完整、可运行,禁止留待办、占位或缺失部分
- 可读性优先:确保代码清晰、易维护
- 避免过度设计:仅使用必要的库和模式
- DRY Principle: Keep code concise, clear, and maintainable; avoid duplication
- Completeness: Code must be complete and runnable; no TODOs, placeholders, or missing parts are allowed
- Readability First: Ensure code is clear and easy to maintain
- Avoid Over-Engineering: Only use necessary libraries and patterns
命名规范
Naming Conventions
文件命名
File Naming
- 组件文件:PascalCase(如 ,
FlowDistributionDlg.vue)AbsWorkbenchView.ts - 工具文件:camelCase(如 ,
validator.ts)http.ts - 常量文件:camelCase(如 ,
constant.ts)config.ts
- Component Files: PascalCase (e.g., ,
FlowDistributionDlg.vue)AbsWorkbenchView.ts - Utility Files: camelCase (e.g., ,
validator.ts)http.ts - Constant Files: camelCase (e.g., ,
constant.ts)config.ts
代码命名
Code Naming
- 类/组件/接口:PascalCase(如 ,
AbsDataModelView)IDataModel - 变量/函数/方法:camelCase(如 ,
modelName)fetchData() - 常量:UPPER_SNAKE_CASE(如 ,
MAX_LENGTH)API_BASE_URL - 私有成员:camelCase,前缀 (如
_)_internalState
- Classes/Components/Interfaces: PascalCase (e.g., ,
AbsDataModelView)IDataModel - Variables/Functions/Methods: camelCase (e.g., ,
modelName)fetchData() - Constants: UPPER_SNAKE_CASE (e.g., ,
MAX_LENGTH)API_BASE_URL - Private Members: camelCase with prefix (e.g.,
_)_internalState
代码组织
Code Organization
导入顺序
Import Order
typescript
// 1. Vue/Vuex 相关
import { Component } from 'vue-property-decorator'
// 2. 第三方库
import { isObject } from '@tdio/utils'
// 3. 项目工具函数
import { getRule } from '@/utils/validator'
// 4. 类型定义
import type { IDataModel } from '../types'
// 5. 组件/视图
import AbsWorkbenchView from '../AbsView'typescript
// 1. Vue/Vuex related
import { Component } from 'vue-property-decorator'
// 2. Third-party libraries
import { isObject } from '@tdio/utils'
// 3. Project utility functions
import { getRule } from '@/utils/validator'
// 4. Type definitions
import type { IDataModel } from '../types'
// 5. Components/Views
import AbsWorkbenchView from '../AbsView'代码结构
Code Structure
typescript
// 1. 装饰器
@Component({ ... })
export default class ComponentName extends BaseView {
// 2. Props
@Prop() value!: Kv
// 3. Refs
@Ref() formRef!: ElForm
// 4. 数据属性
model: Kv = {}
// 5. 计算属性
get computedValue () {
return this.model.value
}
// 6. 方法
validate () {
// ...
}
// 7. 生命周期
mounted () {
// ...
}
}typescript
// 1. Decorators
@Component({ ... })
export default class ComponentName extends BaseView {
// 2. Props
@Prop() value!: Kv
// 3. Refs
@Ref() formRef!: ElForm
// 4. Data properties
model: Kv = {}
// 5. Computed properties
get computedValue () {
return this.model.value
}
// 6. Methods
validate () {
// ...
}
// 7. Lifecycle hooks
mounted () {
// ...
}
}注释规范
Comment Specifications
代码注释
Code Comments
typescript
// ✅ GOOD - 解释复杂逻辑
// 验证模型名称唯一性,需要异步调用接口
async ruleValRepeatVerify (rule, value: string, callback) {
// ...
}
// ❌ BAD - 无意义的注释
// 设置值
setValue (key, value) {
this.$set(this.value, key, value)
}typescript
// ✅ GOOD - Explain complex logic
// Verify the uniqueness of the model name, requires asynchronous API call
async ruleValRepeatVerify (rule, value: string, callback) {
// ...
}
// ❌ BAD - Meaningless comment
// Set value
setValue (key, value) {
this.$set(this.value, key, value)
}函数注释
Function Comments
typescript
// ✅ GOOD - 复杂函数添加注释
/**
* 生成必填验证规则
* @param message 错误提示信息
* @param trigger 触发时机,默认为 'change'
* @returns 验证规则对象
*/
export const genRequired = (message?: string, trigger?: string): IValidateRuleItem => {
// ...
}typescript
// ✅ GOOD - Add comments for complex functions
/**
* Generate required validation rules
* @param message Error prompt message
* @param trigger Trigger timing, default is 'change'
* @returns Validation rule object
*/
export const genRequired = (message?: string, trigger?: string): IValidateRuleItem => {
// ...
}错误处理
Error Handling
typescript
// ✅ GOOD - 明确的错误处理
try {
await this.saveData(this.model!)
} catch (error) {
console.error('保存失败:', error)
this.$message.error('保存失败,请重试')
throw error
}
// ❌ BAD - 忽略错误
try {
await this.saveData(this.model!)
} catch (e) {}typescript
// ✅ GOOD - Clear error handling
try {
await this.saveData(this.model!)
} catch (error) {
console.error('Save failed:', error)
this.$message.error('Save failed, please try again')
throw error
}
// ❌ BAD - Ignore errors
try {
await this.saveData(this.model!)
} catch (e) {}代码变更流程
Code Change Process
- 改动前先简述方案:说明修改内容和原因
- 一次只改一个文件:避免大杂烩式提交
- 仅修改相关代码:不要动无关文件
- 提交前检查:确保代码可运行,无语法错误
- Briefly describe the plan before modification: Explain the content and reason for the change
- Modify only one file at a time: Avoid messy commits
- Only modify relevant code: Do not touch unrelated files
- Check before submission: Ensure code is runnable and free of syntax errors
最佳实践
Best Practices
- 使用工具函数:复用 ,
getRule等工具函数genRequired - 类型安全:充分利用 TypeScript 类型系统
- 国际化:使用 进行文本国际化
$t() - 性能优化:避免不必要的计算和渲染
- 代码审查:提交前进行自我审查
- Use utility functions: Reuse utility functions like ,
getRulegenRequired - Type safety: Make full use of the TypeScript type system
- Internationalization: Use for text internationalization
$t() - Performance optimization: Avoid unnecessary computations and rendering
- Code review: Conduct self-review before submission