laitimes

Front-end code specification

author:Senior Internet Architect

HTML specification

1. Semantic tags

  1. Lists use ul li
  2. 文字使用 p span in cite 等标签
  3. Titles use tags such as h1, h2, etc
  4. 布局使用 section aside header footer article 等 HTML5 布局标签

2. Custom labels

Use the way to write self-closing labels lowercase with underlining

<template>
  <my-owner-components />
</template>
           

3. Multi-feature writing in branches

To improve readability, wrap lines when applying components are written in the order of ref, class, incoming, and outgoing

<template>
  <my-components
    ref="myComponents"
    class="home-my-components"
    :data="data"
    @changeHandle="changeHandle"
  />
</template>
           

4. Use expressions in the line

In the template, Simple Cases Use Expressions Complex Cases Use Computed Properties or Functions

<template>
  <!-- 简单情况 -->
  <div v-show="data.type === 1">
    ...
  </div>
  <!-- 复杂情况 -->
  <div v-show="getTypeShow(data)">
    ...
  </div>
</template>

<script>
export default {
  methods: {
    /**
    * ***显示判断
    * @param data **
    */
    getTypeShow(data) {
      return data.type === 1 && ...
    }
  }
}
</script>
           

5. Avoid repetition

Avoid repeating too much code if there are more than three lines of similar code Configure data recycle traversal

6. Code nesting

According to the element nesting specification, each block element has a separate row, and inline elements are optional

<template>
  <!-- 情况1 -->
  <div>
    <h1></h1>
    <p></p>
    <p><span></span><span></span></p>
  </div>
  <!-- 情况2 -->
  <div>
    <h1></h1>
    <p></p>
    <p>
      <span></span>
      <span></span>
    </p>
  </div>
</template>
           

7、活用 v-if v-show

v-show does not change the DOM tree and does not cause re-rendering for frequent toggles to show hide

v-if changes the DOM tree and causes a re-render to control the display hiding only once

8. Annotation specifications

<template>
  <!-- 标签注释 -->
  <div>
    ...
  </div>
  <!-- 组件注释 -->
  <my-owner-components />
</template>
           

CSS specifications

1. Avoid use

  1. Avoid using label selectors, because in Vue, especially in local components, using label selectors is particularly inefficient and depleting performance, and it is recommended to define classes directly if needed
  2. Except in special cases, it is forbidden to use ID selectors to define styles (except in cases with JS logic)
  3. Avoid using important selectors
  4. Avoid a large number of nesting rules Keep within level 3 For nesting beyond level 4 Consider rewriting or creating new children
  5. Avoid using ID selectors and global label selectors to prevent contamination of global styles

2. Recommended

  1. Extract common styles into the assets file styles by module/function
  2. Use the scoped keyword to constrain the scope in which the style takes effect
  3. Reusable attributes are extracted as page variables as much as possible, which is easy to maintain uniformly
  4. Use mixins to define modules based on functionality, and then call them with @include where needed to avoid re-entering code snippets while coding

3. Writing order

CSS properties are written in order to determine the size of the positioning, width, height, and display first, and then make local details modifications

Positioning (or display) = > width and height = > margin padding => Background Color Definition of cosmetic attributes such as fonts This is defined for better readability, so that others can have a picture of what the final display will look like at a glance

.class-name {
  position: fixed;
  top: 100px;
  left: 0;
  right: 0;
  bottom: 0;
  display: block;
  width: 100%;
  height: 100%;
  margin: 10px;
  padding: 10px;
  background-color: red; 
  border-radius: 2px;
  font-size: 14px;
  color: #000;
  line-height: 1.42;
}
           

4. Style override

The UI framework style needs to be overridden inside the component, and the class name must be added to the outermost component

<template>
  <div class="input-container">
    <el-input class="name-input"></el-input>
  </div>
</template>

<style lang="scss">
.input-container {
  .name-input {
    .el-input__inner {
      font-size: 16px;
    }
  }
}
</style>
           

5. Annotation specifications

Annotate with / annotation content / format Spaces before and after nested subclasses require a carriage return split

/* 注释内容 */
.class-name {
  width: 20px;
  
   /* 这里需要换行 */
  .class-name-l {
    color: blue
  }
}
           

JS specification

1. Usage specification

  1. In vue-cli scaffolding, use the built-in '@' symbol to point to the src development directory to import file resources
  2. 使用 template 或计算属性规避 v-if 和 v-for 用在一起
  3. Uniform use of single quotation marks
  4. Adhere to the single principle of doing only what the function should do within a function, and try to avoid controlling different behaviors through passing in tags
  5. Prioritize trinocular operators, but don't write trinocular operators that are more than 3 layers
  6. For example, some debugged console statements and useless deprecated code must be deleted in a timely manner
  7. The method of requesting data uses try catch error catch to note the execution callback

2. Component sequence specification

<script>
export default {
  name: 'ExampleName',        // 这个名字推荐:大写字母开头驼峰法命名
  props: {},                  // Props 定义
  components: {},             // 组件定义
  directives: {},             // 指令定义
  mixins: [],                 // 混入 Mixin 定义。
  data () {                   // Data 定义。
    return {
      dataProps: ''           // Data 属性的每一个变量都需要在后面写注释说明用途,就像这样
    }
},
  computed: {},               // 计算属性定义。
  watch: {},                  // 属性变化监听器。
  created () {},              // 生命钩子函数,按照他们调用的顺序。
  mounted () {},              // 挂载到元素。
  activated () {},            // 使用 keep-alive 包裹的组件激活触发的钩子函数。
  deactivated () {},          // 使用 keep-alive 包裹的组件离开时触发的钩子函数
  methods: {                  // 组件方法定义。
    publicbFunction () {}     // 公共方法的定义,可以提供外面使用
    _privateFunction () {}    // 私有方法,下划线定义,仅供组件内使用。多单词,注意与系统名字冲突!
  }
}
</script>
           

3. Annotation specifications

Function/method comments must contain a description of the function, and must be identified with arguments and return values, its author, dependencies, and compatibility information.

  1. Single-line comments: Double slashes should be followed by spaces and the indentation should be consistent with the contextual code, or comments at the end of the line, where left and right spaces are still required
// 注释
const userID = 24
const userID = 12 // 注释
           
  1. Multi-line comments: Generally used to comment on code that is difficult to understand, may contain errors, and has strong logic, and is indented consistently
/*
 * 针对下方代码的说明
 * 第一行太长写第二行
 */
const aa = 1
           
  1. Function Comments: Specify the name and type of the input parameters, and recommend the full comments in the following format
/**
 * @Description 加入购物车
 * @Author luochen_ya
 * @Date 2024-03-13
 * @param {Number} goodId 商品id
 * @param {Array<Number>} specs sku规格
 * @param {Number} amount 数量
 * @param {String} remarks 备注
 * @returns <Promise> 购物车信息
 */
apiProductAddCard = (goodId, specs, amount, remarks) => {
  return axios.post('***', { goodId, specs, amount, remarks })
}
           
  1. File Notes: Specify the description of the file
/**
 * @Description: 文件描述
 * @Author: luochen_ya
 * @Date: 2024-03-13
 */
           

Naming conventions

1. Directory naming

Named after the small hump in lowercase

  1. 项目文件夹:projectName
  2. 样式文件夹:css / scss
  3. Script folder: js

2. Picture naming

The picture starts with img and the icon starts with icon

  1. img_ feature_module_number
  2. icon_ feature_module_number

3. File naming

  1. According to the small hump command, if the English word is too long or more than 2 words, it can be abbreviated to the first four columns, such as :comming_soon.png and so on
  2. 有复数含义 采用复数命名列如:minixs styles images icons 等
  3. Static resources are named in lowercase + underscore columns, such as :icon_arrow.png img_logo.png and so on
  4. The component is named as a small hump Common components with gd prefix columns, such as: gdOwnerComponents, etc

4, Method Naming

Method naming is different from file naming, try to be complete in English, and the semantic expression should be complete and clear

  1. According to the hump nomenclature, common verb conventions can be used
  • can: Determine whether an action can be executed The function returns a boolean value of true executable and false unexecutable
  • has: Determine whether it contains a certain value The function returns a boolean value true containing this value false does not contain this value
  • is: To determine whether it is a certain value, the function returns a boolean value true is a certain value and false is not a certain value
  • get: Get a value function returns a non-Boolean value
  • set: Set a value that returns no value or whether the load is complete
  1. Semantic English naming Only the internal usage method of the component is distinguished by _ (underscore).
<script>
export default {
  methods: { // 组件方法定义
    publicbFunction () {} // 公共方法的定义 可以提供外面使用
    _privateFunction () {} // 私有方法 下划线定义 仅供组件内使用
  }
}
</script>
           
  1. Introducing components: Camel naming with capital letters
import MyOwnerComponents from '@/components/MyOwnerComponents'
           
  1. Variables: Use camel naming Prioritize let const to avoid var
let userName = 'luochen_ya'
const userInfo = {
  name: 'luochen_ya',
  age: 24
}
           
  1. Constant: All letters are capitalized and divided by the following dash
const Constant = {
  // 公用状态
  COMMON_STATUS_ENABLE = 1, // 启用
  COMMON_STATUS_DISABLE = 2, // 停用
}
           

5. Style naming

Class names start with lowercase letters, lowercase letters, hyphens, and numbers Here are some commonly used class names

  1. 包裹层: .xxx-wrap
  2. 列表: .xxx-list
  3. 列表项: .xxx-list-item
  4. 左边内容: .xxx-left
  5. 中间内容: .xxx-middle
  6. 右边内容: .xxx-right
  7. 某个页面:.xxx-page

6. Common words

  1. Commonly used verbs
  • get => 取值
  • set => gives a value
  • add => New
  • remove => 移除
  • show = > display
  • hide => 隐藏
  • view => 查看
  • browse => 浏览
  • edit => modify
  • save => 保存
  • delete = > delete
  • find => query
  • undo => 撤销
  • redo => redo
  • clean = > clear
  • index => 索引
  • observe => 观察
  • send = > send
  • receive => 接收
  • refresh => 刷新
  • synchronize => 同步
  1. Commonly used abbreviations
  • object => obj
  • array => arr
  • function => fn
  • message => msg
  • button => btn

Engineering structures

1. Directory construction

├── api                       所有api接口
├── assets                    靜態資源
│   ├── fonts                   全局公用字体
│   ├── icons                   全局公用图标
│   ├── images                  全局公用图片
│   └── styles                  全局公用样式
├── components                公用組件
│   ├── base                    基础组件
│   └── business                业务组件
├── constants                 常量 统一管理
├── locales                   多语言管理
├── plugins                   插件 统一管理
├── router                    路由 统一管理
│   └── index.js               
├── store                     vuex 统一管理
│   ├── modules                 
│   ├── getters.js              
│   └── index.js                
├── utils                     工具函数 统一管理
├── views                     视图目录(所有业务逻辑的页面)
           

2. Code style

You can use eslint directly to enforce a unified code specification, and you can avoid some syntax errors, or you can configure eslint to use it according to the following definitions

The following are personal habits for reference only

  1. The first line is indented by 2 spaces
  2. Semicolons are removed from the js code
  3. If the HTML code exceeds 255 characters, a line break is performed
  4. JS code uniformly uses single or double quotes

Author: luochen_ya

Link: https://juejin.cn/post/7345666534997901366