前端Vue3项目代码开发规范

前端Vue3项目代码开发规范

这是一份专为 Vue3 技术栈设计的前端开发规范标准,由于目前项目小组刚组建,前端代码编写暂未形成规范,故结合 GitHub 流行规范(如 Airbnb、Vue 官方风格指南)和工程化实践,梳理出了一份前端项目开发规范标准以备小组成员共享,文档包含四个核心模块:


一、代码书写规范

1. Vue 组件规范
  • 组件结构顺序(单文件组件 SFC)

    xml 复制代码
    <template>   <!-- 最多一个顶级元素 -->
      <div>...</div>
    </template>
    ​
    <script setup>  // 使用 Composition API + <script setup>
    // 导入顺序:Vue → 第三方库 → 组件 → 工具类 → 样式
    import { ref, computed } from 'vue'
    import { useUserStore } from '@/stores/user'
    import BaseButton from './BaseButton.vue'
    </script>
    ​
    <style scoped>  <!-- 强制 scoped 或 CSS Modules -->
    .component-block { ... }
    </style>
  • 命名约定

    • 组件名:PascalCase(如 UserProfile.vue
    • 自定义事件:kebab-case(如 @update-value
    • Props:camelCase 声明,模板中使用 kebab-case
2. Pinia 状态管理
dart 复制代码
// stores/user.ts
export const useUserStore = defineStore('user', () => {
  // State
  const username = ref('')
  
  // Actions
  const fetchUser = async () => { 
    const res = await axios.get('/api/user') 
    username.value = res.data.name
  }
  
  // Getters
  const isLoggedIn = computed(() => !!username.value)
  
  return { username, fetchUser, isLoggedIn }
})
3. 路由规范(Vue Router)
javascript 复制代码
// router/index.ts
const routes = [
  {
    path: '/user/:id',
    name: 'user-profile', // 路由名使用 kebab-case
    component: () => import('@/views/UserProfile.vue'), // 动态导入
    meta: { requiresAuth: true }
  }
]

二、文件命名规范

类型 命名规则 示例
Vue 组件 PascalCase SearchInput.vue
页面视图 PascalCase UserDashboard.vue
Pinia Store camelCase useCartStore.ts
工具函数 camelCase formatCurrency.js
路由文件 kebab-case admin-routes.ts
资产文件 kebab-case icon-arrow-right.svg

目录结构示例

csharp 复制代码
src/
├── components/
│   ├── base/               // 基础组件
│   │   └── BaseButton.vue
│   └── layout/
├── views/
│   └── UserProfile.vue
├── stores/
│   └── useCartStore.ts
├── utils/
│   └── dateFormatter.ts
└── api/
    └── authApi.ts          // API 模块化封装

三、Git 提交规范

采用 Conventional Commits 标准:

makefile 复制代码
<type>(<scope>): <subject>
# 示例
feat(user): add password reset UI
fix(router): handle 404 redirect
chore(deps): upgrade axios to 1.2.0

常用 type

  • feat:新功能
  • fix:Bug 修复
  • docs:文档变更
  • style:代码样式调整
  • refactor:重构(不修复 bug 也不增加功能)
  • test:测试相关
  • chore:构建/工具变更

四、代码校验规范

1. 工具链配置
bash 复制代码
# 必备依赖
npm install -D eslint prettier eslint-plugin-vue @typescript-eslint/parser 
eslint-config-prettier husky lint-staged
2. ESLint 配置(.eslintrc.cjs)
java 复制代码
module.exports = {
  root: true,
  env: { browser: true, es2021: true },
  extends: [
    'eslint:recommended',
    'plugin:vue/vue3-recommended',
    'plugin:prettier/recommended' 
  ],
  rules: {
    'vue/multi-word-component-names': 'off', // 允许单单词组件名
    'vue/no-unused-vars': 'error',
    'vue/component-api-order': ['error', { // Composition API 顺序
      order: ['setup', 'props', 'data', 'computed', 'methods', 'lifecycle']
    }]
  }
}
3. Prettier 配置(.prettierrc)
json 复制代码
{
  "semi": false,
  "singleQuote": true,
  "trailingComma": "es5",
  "printWidth": 100,
  "htmlWhitespaceSensitivity": "ignore"
}
4. Git Hook 自动化(package.json)
json 复制代码
{
  "scripts": {
    "lint": "eslint . --ext .js,.ts,.vue --fix",
    "prepare": "husky install"
  },
  "lint-staged": {
    "*.{js,ts,vue}": ["eslint --fix", "prettier --write"],
    "*.{css,scss}": ["stylelint --fix"]
  }
}

初始化流程

sql 复制代码
npx husky install
npx husky add .husky/pre-commit "npx lint-staged"

五、附加工程化建议

  1. IDE 统一:推荐 VSCode + 插件:

    • Vue Language Features (Volar)
    • ESLint / Prettier
    • EditorConfig
  2. 提交信息校验

    bash 复制代码
    npm install -D @commitlint/cli @commitlint/config-conventional
    echo "module.exports = { extends: ['@commitlint/config-conventional'] }" > .commitlintrc.js
    npx husky add .husky/commit-msg 'npx commitlint --edit $1'
  3. CI/CD 集成(示例:GitHub Actions):

    yaml 复制代码
    jobs:
      lint:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
          - run: npm install
          - run: npm run lint

执行策略

  1. 将规范文档存入项目根目录 /docs/frontend-standard.md
  2. 首次会议宣讲规范,使用脚手架初始化校验工具
  3. 代码审查时重点检查规范符合度
  4. 每月迭代优化规范内容

通过此规范可显著提升代码一致性、降低维护成本,同时为后续项目扩展奠定基础。

相关推荐
前端工作日常2 小时前
我理解的`npm pack` 和 `npm install <local-path>`
前端
李剑一3 小时前
说个多年老前端都不知道的标签正确玩法——q标签
前端
嘉小华3 小时前
大白话讲解 Android屏幕适配相关概念(dp、px 和 dpi)
前端
姑苏洛言3 小时前
在开发跑腿小程序集成地图时,遇到的坑,MapContext.includePoints(Object object)接口无效在组件中使用无效?
前端
奇舞精选3 小时前
Prompt 工程实用技巧:掌握高效 AI 交互核心
前端·openai
Danny_FD3 小时前
React中可有可无的优化-对象类型的使用
前端·javascript
用户757582318553 小时前
混合应用开发:企业降本增效之道——面向2025年移动应用开发趋势的实践路径
前端
P1erce3 小时前
记一次微信小程序分包经历
前端
LeeAt3 小时前
从Promise到async/await的逻辑演进
前端·javascript
等一个晴天丶3 小时前
不一样的 TypeScript 入门手册
前端