规范目的

提高团队协作效率
便于前端后期优化维护
输出高质量的文档

命名规范

为了让大家书写可维护的代码,而不是一次性的代码
让团队当中其他人看你的代码能一目了然
甚至一段时间时候后你再看你某个时候写的代码也能看

普通变量命名规范

  • 命名方法 :驼峰命名法
  • 命名规范 :

    1. 命名必须是跟需求的内容相关的词,比如说我想申明一个变量,用来表示我的学校,那么我们可以这样定义const mySchool = “我的学校”;
    2. 命名是复数的时候需要加s,比如说我想申明一个数组,表示很多人的名字,那么我们可以这样定义const names = new Array();

      常量

  • 命名方法 : 全部大写

  • 命名规范 : 使用大写字母和下划线来组合命名,下划线用以分割单词。
    1. const MAX_COUNT = 10
    2. const URL = 'https://www.baidu.com/'

    组件命名规范

官方文档推荐及使用遵循规则:

PascalCase (单词首字母大写命名)是最通用的声明约定
kebab-case (短横线分隔命名) 是最通用的使用约定

  • 组件名应该始终是多个单词的,根组件 App 除外
  • 有意义的名词、简短、具有可读性
  • 命名遵循 PascalCase 约定
    • 公用组件以 Abcd (公司名缩写简称) 开头,如(AbcdDatePicker,AbcdTable)
    • 页面内部组件以组件模块名简写为开头,如(StaffBenchToCharge,StaffBenchAppNotArr)
  • 使用遵循 kebab-case 约定
    • 在页面中使用组件需要前后闭合,并以短线分隔,如(
  • 导入及注册组件时,遵循 PascalCase 约定
  • 同时还需要注意:必须符合自定义元素规范: 切勿使用保留字。

method 方法命名命名规范

  • 驼峰式命名,统一使用动词或者动词+名词形式

    //bad go、nextPage、show、open、login // good jumpPage、openCarInfoDialog

  • 请求数据方法,以 data 结尾

    //bad takeData、confirmData、getList、postForm // good getListData、postFormData

  • init、refresh 单词除外

  • 尽量使用常用单词开头(set、get、go、can、has、is)

附: 函数方法常用的动词:
get 获取/set 设置
add 增加/remove 删除
start 启动/stop 停止
open 打开/close 关闭
read 读取/write 写入
save 保存/cancel 取消
create 创建/destroy 销毁
begin 开始/end 结束
backup 备份/restore 恢复
import 导入/export 导出
split 分割/merge 合并
inject 注入/extract 提取
attach 附着/detach 脱离
bind 绑定/separate 分离
view 查看/browse 浏览
edit 编辑/modify 修改,
select 选取/mark 标记
copy 复制/paste 粘贴
undo 撤销/redo 重做
insert 插入/delete 移除
append 附加/subtract 减去
clean 清理/clear 清除
index 索引/sort 排序
find 查找/search 搜索
increase 增加/decrease 减少
play 播放/pause 暂停
launch 启动/run 运行
compile 编译/execute 执行
debug 调试/trace 跟踪
observe 观察/listen 监听
build 构建/publish 发布
input 输入/output 输出
encode 编码/decode 解码
encrypt 加密/decrypt 解密
compress 压缩/decompress 解压缩
pack 打包/unpack 解包,
parse 解析/emit 生成
connect 连接/disconnect 断开
send 发送/receive 接收
download 下载/upload 上传
synchronize 同步/异步 Asynchronous
update 更新/revert 复原/refresh 刷新
lock 锁定/unlock 解锁
check out 签出/check in 签入
submit 提交/commit 交付
push 推/pull 拉
expand 展开/collapse 折叠
start 开始/finish 完成
enter 进入/exit 退出
abort 放弃/quit 离开
obsolete 废弃/depreciate 废旧
collect 收集/aggregate 聚集

props 命名

在声明 prop 的时候,其命名应该始终使用 camelCase,而在模板中应该始终使用 kebab-case

  1. <!-- bad -->
  2. <script> props: { 'greeting-text': String } </script>
  3. <welcome-message greetingText="hi"></welcome-message>
  4. <!-- good -->
  5. <script> props: { greetingText: String } </script>
  6. <welcome-message greeting-text="hi"></welcome-message>

router

Vue Router Path 命名采用 kebab-case 格式。 用 Snake(如:/user_info)或 camelCase(如:/userInfo)的单词会被当成一个单词,搜索引擎无法区分语义

  1. // bad
  2. {
  3. path: '/user_info', // user_info 当成一个单词
  4. name: 'UserInfo',
  5. component: UserInfo,
  6. meta: {
  7. title: ' - 用户',
  8. desc: ''
  9. }
  10. },
  11. // good
  12. {
  13. path: '/user-info', // 能解析成 user info
  14. name: 'UserInfo',
  15. component: UserInfo,
  16. meta: {
  17. title: ' - 用户',
  18. desc: ''
  19. }
  20. },

模板中组件

对于绝大多数项目来说,在单文件组件和字符串模板中组件名应该总是 PascalCase 的,但是在 DOM 模板中总是 kebab-case 的。

  1. <!-- 在单文件组件和字符串模板中 -->
  2. <MyComponent/>
  3. <!-- 在 DOM 模板中 -->
  4. <my-component></my-component>

例外情况

  1. 作用域不大临时变量可以简写,比如:str,num,bol,obj,fun,arr。
  2. 循环变量可以简写,比如:i,j,k 等。

    结构化规范

    目录文件夹及子文件规范

  • 以下统一管理处均对应相应模块
  • 以下全局文件文件均以 index.js 导出,并在 main.js 中导入
  • 以下临时文件,在使用后,接口已经有了,发版后清除
  1. my-project-name/
  2. |- BuildScript // 流水线部署文件目录
  3. |- docs // 项目的细化文档目录(可选)
  4. |- nginx // 部署在容器上前端项目 nginx 代理文件目录
  5. |- node_modules // 下载的依赖包
  6. |- public // 静态页面目录
  7. |- index.html // 项目入口
  8. |- src // 源码目录
  9. |- api // http 请求目录
  10. |- assets // 静态资源目录,这里的资源会被wabpack构建
  11. |- icon // icon 存放目录
  12. |- img // 图片存放目录
  13. |- js // 公共 js 文件目录
  14. |- scss // 公共样式 scss 存放目录
  15. |- frame.scss // 入口文件
  16. |- global.scss // 公共样式
  17. |- reset.scss // 重置样式
  18. |- components // 组件
  19. |- plugins // 插件
  20. |- router // 路由
  21. |- routes // 详细的路由拆分目录(可选)
  22. |- index.js
  23. |- store // 全局状态管理
  24. |- utils // 工具存放目录
  25. |- request.js // 公共请求工具
  26. |- views // 页面存放目录
  27. |- App.vue // 根组件
  28. |- main.js // 入口文件
  29. |- tests // 测试用例
  30. |- .browserslistrc// 浏览器兼容配置文件
  31. |- .editorconfig // 编辑器配置文件
  32. |- .eslintignore // eslint 忽略规则
  33. |- .eslintrc.js // eslint 规则
  34. |- .gitignore // git 忽略规则
  35. |- babel.config.js // babel 规则
  36. |- Dockerfile // Docker 部署文件
  37. |- jest.config.js
  38. |- package-lock.json
  39. |- package.json // 依赖
  40. |- README.md // 项目 README
  41. |- vue.config.js // webpack 配置

vue 文件基本结构

  1. <template>
  2. <div>
  3. <!--必须在div中编写页面(vue2适用)-->
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. components : {
  9. },
  10. data () {
  11. return {
  12. }
  13. },
  14. mounted() {
  15. },
  16. methods: {
  17. }
  18. }
  19. </script>
  20. <!--声明语言,并且添加scoped-->
  21. <style lang="scss" scoped>
  22. </style>

多个特性的元素规范

多个特性的元素应该分多行撰写,每个特性一行。(增强更易读)

  1. <!-- bad -->
  2. <img src="https://vuejs.org/images/logo.png" alt="Vue Logo">
  3. <my-component foo="a" bar="b" baz="c"></my-component>
  4. <!-- good -->
  5. <img
  6. src="https://vuejs.org/images/logo.png"
  7. alt="Vue Logo"
  8. >
  9. <my-component
  10. foo="a"
  11. bar="b"
  12. baz="c"
  13. >
  14. </my-component>

元素特性的顺序

原生属性放前面,指令放后面
如下所示:
- class
- id,ref
- name
- data-
- src, for, type, href,value,max-length,max,min,pattern
- title, alt,placeholder
- aria-
, role
- required,readonly,disabled
- is
- v-for
- key
- v-if
- v-else-if
- v-else
- v-show
- v-cloak
- v-pre
- v-once
- v-model
- v-bind,:
- v-on,@
- v-html
- v-text

组件选项顺序

如下所示:
- components
- props
- data
- computed
- created
- mounted
- metods
- filter
- watch

注释规范

代码注释在一个项目的后期维护中显的尤为重要,所以我们要为每一个被复用的组件编写组件使用说明,为组件中每一个方法编写方法说明

务必添加注释列表

  1. 公共组件使用说明
  2. 各组件中重要函数或者类说明
  3. 复杂的业务逻辑处理说明
  4. 特殊情况的代码处理说明,对于代码中特殊用途的变量、存在临界值、函数中使用的 hack、使用了某种算法或思路等需要进行注释描述
  5. 多重 if 判断语句
  6. 注释块必须以/(至少两个星号)开头/
  7. 单行注释使用//

    单行注释

注释单独一行,不要在代码后的同一行内加注释。例如:

  1. //bad
  2. var name =”abc”; // 姓名
  3. //good
  4. // 姓名
  5. var name = abc”;

多行注释

组件使用说明,和调用说明

  1. /**
  2. * 组件名称
  3. * @module 组件存放位置
  4. * @desc 组件描述
  5. * @author 组件作者
  6. * @date 2021年08月20日00:00:00
  7. * @param {Object} [title] - 参数说明
  8. * @param {String} [columns] - 参数说明
  9. * @example 调用示例
  10. * <hbTable :title="title" :columns="columns" :tableData="tableData"></hbTable>
  11. **/

文件注释

每个文件都应该添加注释,可以为阅读代码的人节省大量时间

  1. /*
  2. * @Author: fairysd
  3. * @Date: 2021-08-16 10:08:39
  4. * @LastEditTime: 2021-09-07 11:25:33
  5. * @LastEditors: fairysd
  6. * @Description:
  7. * @FilePath: c:\Users\Administrator\AppData\Roaming\Code\User\settings.json
  8. */

函数注释

函数注释如下

  1. /**
  2. * @description:
  3. * @param {*}
  4. * @return {*}
  5. */

特殊标记

有时我们发现某个可能的 bug,但因为一些原因还没法修复;或者某个地方还有一些待完成的功能,这时我们需要使用相应的特殊标记注释来告知未来的自己或合作者。常用的特殊标记有两种:

  • // FIXME : 说明问题是什么
  • // TODO : 说明还要做什么或者问题的解决方案

    1. class Calculator extends Abacus {
    2. constructor () {
    3. super ()
    4. // FIXME: shouldn’t use a global here
    5. total = 0
    6. // TODO: total should be configurable by an options param
    7. this.total = 0
    8. }
    9. }

    编码规范

优秀的项目源码,即使是多人开发,看代码也如出一人之手。统一的编码规范,可使代码更易于阅读,易于理解,易于维护。尽量按照 ESLint 格式要求编写代码

源码风格

使用 ES6 风格编码

  1. 定义变量使用 let ,定义常量使用 const
  2. 静态字符串一律使用单引号或反引号,动态字符串使用反引号

    1. // bad
    2. const a = 'foobar'
    3. const b = 'foo' + a + 'bar'
    4. // acceptable
    5. const c = `foobar`
    6. // good
    7. const a = 'foobar'
    8. const b = `foo${a}bar`
    9. const c = 'foobar'
  3. 解构赋值

  • 数组成员对变量赋值时,优先使用解构赋值

    1. // 数组解构赋值 const arr = [1, 2, 3, 4]
    2. // bad
    3. const first = arr[0]
    4. const second = arr[1]
    5. // good
    6. const [first, second] = arr
  • 函数的参数如果是对象的成员,优先使用解构赋值

    1. // 对象解构赋值
    2. // bad
    3. function getFullName(user) {
    4. const firstName = user.firstName
    5. const lastName = user.lastName
    6. }
    7. // good
    8. function getFullName(obj) {
    9. const { firstName, lastName } = obj
    10. }
    11. // best
    12. function getFullName({ firstName, lastName }) {}
  1. 拷贝数组

使用扩展运算符(…)拷贝数组。

  1. const items = [1, 2, 3, 4, 5]
  2. // bad
  3. const itemsCopy = items
  4. // good
  5. const itemsCopy = [...items]
  1. 箭头函数

需要使用函数表达式的场合,尽量用箭头函数代替。因为这样更简洁,而且绑定了 this

  1. // bad const self = this;
  2. const boundMethod = function(...params) {
  3. return method.apply(self, params);
  4. }
  5. // acceptable
  6. const boundMethod = method.bind(this);
  7. // best
  8. const boundMethod = (...params) => method.apply(this, params);
  1. 模块
  • 如果模块只有一个输出值,就使用 export default,如果模块有多个输出值,就不使用 export default

    1. // bad import * as myObject from './importModule'
    2. // good
    3. import myObject from './importModule'
  • 如果模块默认输出一个函数,函数名的首字母应该小写。

    1. function makeStyleGuide() { }
    2. export default makeStyleGuide;
  • 如果模块默认输出一个对象,对象名的首字母应该大写。 ```javascript const StyleGuide = {
    es6: { } };

export default StyleGuide;

  1. <a name="nZOfk"></a>
  2. ## 指令规范
  3. 1. 指令有缩写一律采用缩写形式
  4. ```vue
  5. // bad
  6. v-bind:class="{'show-left':true}"
  7. v-on:click="getListData"
  8. // good
  9. :class="{'show-left':true}"
  10. @click="getListData"
  1. v-for 循环必须加上 key 属性,在整个 for 循环中 key 需要唯一(不要使用index作为key值)

    1. <!-- good -->
    2. <ul>
    3. <li v-for="todo in todos" :key="todo.id">
    4. {{ todo.text }}
    5. </li>
    6. </ul>
    7. <!-- bad -->
    8. <ul>
    9. <li v-for="todo in todos">
    10. {{ todo.text }}
    11. </li>
    12. </ul>
  2. 避免 v-if 和 v-for 同时用在一个元素上(性能问题,vue3不会因此影响性能)

  • 将数据替换为一个计算属性,让其返回过滤后的列表

    1. <!-- bad -->
    2. <ul>
    3. <li v-for="user in users" v-if="user.isActive" :key="user.id">
    4. {{ user.name }}
    5. </li>
    6. </ul>
    7. <!-- good -->
    8. <ul>
    9. <li v-for="user in activeUsers" :key="user.id">
    10. {{ user.name }}
    11. </li>
    12. </ul>
    13. <script>
    14. computed: {
    15. activeUsers: function () {
    16. return this.users.filter(function (user) {
    17. return user.isActive
    18. })
    19. }
    20. }
    21. </script>
  • 将 v-if 移动至容器元素上 (比如 ul, ol)

    1. <!-- bad -->
    2. <ul>
    3. <li v-for="user in users" v-if="shouldShowUsers" :key="user.id">
    4. {{ user.name }}
    5. </li>
    6. </ul>
    7. <!-- good -->
    8. <ul v-if="shouldShowUsers">
    9. <li v-for="user in users" :key="user.id">
    10. {{ user.name }}
    11. </li>
    12. </ul>

    Props 规范

Props 定义应该尽量详细

  1. // bad 这样做只有开发原型系统时可以接受
  2. props: ['status']
  3. // good
  4. props: {
  5. status: {
  6. type: String,
  7. required: true,
  8. validator: function (value) {
  9. return [
  10. 'syncing',
  11. 'synced',
  12. 'version-conflict',
  13. 'error'
  14. ].indexOf(value) !== -1
  15. }
  16. }
  17. }

其他

  1. 避免 this.$parent
  2. 调试信息 console.log() debugger 使用完及时删除
  3. 除了三目运算,if,else 等禁止简写

    1. // bad
    2. if (true)
    3. alert(name);
    4. console.log(name);
    5. // bad
    6. if (true)
    7. alert(name);
    8. console.log(name)
    9. // good
    10. if (true) {
    11. alert(name);
    12. }
    13. console.log(name);

    CSS 规范

    通用规范

  4. 统一使用”-“连字符

  5. 省略值为 0 时的单位

    1. // bad
    2. padding-bottom: 0px;
    3. margin: 0em;
    4. // good
    5. padding-bottom: 0;
    6. margin: 0;
  6. 如果 CSS 可以做到,就不要使用 JS

  7. 声明应该按照以下顺序

    1. 布局定位属性:display / position / float / clear / visibility / overflow
    2. 自身属性:width / height / margin / padding / border / background
    3. 文本属性:color / font / text-decoration / text-align / vertical-align / white- space / break-word
    4. 其他属性(CSS3):content / cursor / border-radius / box-shadow / text-shadow / background: linear-gradient …
      1. .box {
      2. display: block;
      3. position: relative;
      4. float: left;
      5. width: 100px;
      6. height: 100px;
      7. margin: 0 10px;
      8. padding: 20px 0;
      9. font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
      10. color: #333;
      11. background: rgba(0,0,0,.5);
      12. -webkit-border-radius: 10px;
      13. -moz-border-radius: 10px;
      14. -o-border-radius: 10px;
      15. -ms-border-radius: 10px;
      16. border-radius: 10px;
      17. }
  8. 元素选择器应该避免在 scoped 中出现

官方文档说明:在 scoped 样式中,类选择器比元素选择器更好,因为大量使用元素选择器是很慢的。

  1. 左括号与类名之间一个空格,冒号与属性值之间一个空格

    1. //bad
    2. .box{
    3. width:100%;
    4. }
    5. //good
    6. .box {
    7. width: 100%;
    8. }
  2. 逗号分隔的取值,逗号之后一个空格

    1. //bad
    2. .box {
    3. box-shadow: 1px 1px 1px #333,2px 2px 2px #ccc;
    4. }
    5. //good
    6. .jdc {
    7. box-shadow: 1px 1px 1px #333, 2px 2px 2px #ccc;
    8. }
  3. 颜色值 rgb() rgba() hsl() hsla() rect() 中不需有空格,且取值不要带有不必要的 0。

    1. //bad
    2. .box {
    3. color: rgba( 255, 255, 255, 0.5 );
    4. }
    5. //good
    6. .box {
    7. color: rgba(255,255,255,.5);
    8. }

    sass 规范

  4. 当使用 Sass 的嵌套功能的时候,重要的是有一个明确的嵌套顺序,以下内容是一个 SCSS 块应具有的顺序。

    1. 当前选择器的样式属性
    2. 父级选择器的伪类选择器 (:first-letter, :hover, :active etc)
    3. 伪类元素 (:before and :after)
    4. 父级选择器的声明样式 (.selected, .active, .enlarged etc.)
    5. 用 Sass 的上下文媒体查询
    6. 子选择器作为最后的部分 ```css .product-teaser { // a. Style attributes display: inline-block; padding: 1rem; background-color: whitesmoke; color: grey;

      // b. Pseudo selectors with parent selector &:hover { color: black; }

      // c. Pseudo elements with parent selector &:before { content: “”; display: block; border-top: 1px solid grey; }

      &:after { content: “”; display: block; border-top: 1px solid grey; }

      // d. State classes with parent selector &.active { background-color: pink; color: red;

      // 4.2. Pseuso selector in state class selector &:hover { color: darkred; } }

      // e. Contextual media queries @media screen and (max-width: 640px) { display: block; font-size: 2em; }

      // f. Sub selectors

      .content > .title { font-size: 1.2em;

      // f.5. Contextual media queries in sub selector @media screen and (max-width: 640px) { letter-spacing: 0.2em; text-transform: uppercase; } } }

  1. <a name="hRu7N"></a>
  2. ## 特殊规范
  3. - 对于页面级组件样式,应该是有作用域的
  4. - 对于公用组件或者全局组件库,我们应该更倾向于选用基于 class 的 BEM 策略
  5. ```css
  6. <style lang='scss'></style> // bad
  7. <!-- 使用 scoped 作用域 -->
  8. <style lang='scss' scoped></style> // good
  9. <!-- 使用 BEM 约定 -->
  10. <style> // good
  11. .c-Button {
  12. border: none;
  13. border-radius: 2px;
  14. }
  15. .c-Button--close {
  16. background-color: red;
  17. }
  18. </style>

参考

风格指南
前端js规范文档