Front-end code writing specifications

JS code format specification

       js文件, vue文件, 及jsx文件都遵循eslint规范, 而且在.eslintrc.js 对eslint进行一些配置, 我们遵循业界通用代码规范, 去除一些鸡肋的限制, 详情可见[eslint-rules](https://eslint.org/docs/rules/)

      注意: 我们本地开发时候, 会有eslint进行预检查, 如果有不符合规范的代码, 是不能进行开发的, 我们需统一代码风格, 有时候多一个空格少一个空格都会报错, 可以参考其他上线的案例, 也可以去[eslint-rules](https://eslint.org/docs/rules/)详细看看

vue specification

     [vue风格指南](https://cn.vuejs.org/v2/style-guide/)

Naming the file name

推荐: 文件(文件夹)名单词间隔用“-”隔开,不要采用大小写(因为windows路径不识别大小写)

     例如:item-scroll.jsx、inner-top.vue、class-list/
有的项目喜欢组件大驼峰方式, 如果保证项目统一性, 可继续保留组首字母大写风格, 如: ItemScroll.js, InnerTop.vue, ClassList/
     有的项目是交接过来的, 里面什么命名都有, 那么新页面, 我们统一用 '-' 来命名, 不要一会儿驼峰, 一会全部大写, 一会中杆那么随意

Methods variable names named

    命名不能随意想咋写咋写, 是为了更好的方便阅读, 保证代码整洁性, 统一性

Categories: large hump

function Tab () {
     
}
 
class Scroll () {
     
}

Variable, function: small hump
// variable straightforward, do not smack of logic and action

let count = 10
let flag = false
// bad
let getFlag = true
 
 
// Boolean 类型推荐加个前缀 is
let isCreated = true
 
// 数据拉取推荐加个前缀 get
function getInfo () {
     
}
 
// 赋值等操作推荐加个前缀 set
const setInfo = function () {
 
}
 
//  如果是事件推荐前面加个on 或 handle
const onTabChange = function () {}
const handleScroll = function () {}

Constants: all uppercase, separated from the bottom bar '_'

const MAX_LIMIT = 10
const LIMIT = 10

When to use private?

1 to determine what properties and methods are private? Why do some function, and some private is named, some not private name?
2 private property outside can get to?
This is a question to be discussed in detail, the concept of private is the concept of a static language, js as a dynamic language, you need to achieve in a private development stage by some plug-ins, but the meaning is not too large, so more private can only be a convention.
principle: as long as access inside and not to have exposed can call private (even if the external likely to visit, but not deliberately exposed interface), usually the development phase, if not deliberately tangled private

let _a = 1
const _getList = () => {}

Examples of errors:

const a = 1
const a_b = 2
const a_B = 3
const getinfo = () => {}
const MAX_list = 10
const obj123456 = {}
const item1 = {}
const item2 = {}
const item3 = {}
const Tab = 'a'

Examples of basic components

/**
 * 注意:
 * 自定义事件 一定要在顶部申明, 加上详细注释, 包括事件类型, 传递参数, 参数类型, 参数状态等
 */
const events = {
  CLICK: 'click'
}
 
/**
 * 注意:
 * 自定义组件 一定要在顶部申明, 加上详细注释, 包括事件类型, 传递参数, 参数类型, 参数状态等
 *
 * button组件
 * @module components/button
 * @desc 按钮
 * @param {String} [type=default] - 显示类型, 接收 default, primary, danger
 * @param {Boolean} [disbale=false] - 禁用
 * @param {String} [size=large] - 尺寸, 接收 normal, small, large
 *
 * @example
 * <button @click="clickHandle" size="large" type="primary">按钮</button>
 */
const props = {
  disable: Boolean,
  size: {
    type: String,
    default: 'normal'
  },
  type: {
    type: String,
    default: 'default'
  }
}

Components page example

 /**
     * 注意:
     * 基础组件css命名空间为 c-
     *
     * 外层容器样式命名 c-文件名
     * 子元素样式命名 c-文件名-样式名
     * 条件样式命名 c-文件名--样式名
     */
     
    <a
      class="c-button"
      :class="[
        `c-button--${type}`,
        `c-button--${size}`,
        {
          'c-button-disabled': disabled,
          'c-button-plain': plain
        }
      ]"
    >
      <text
        class="c-button-text"
        :class="[`c-button-${type}-text`]"
      >
        <slot></slot>
      </text>
    </a>

**业务逻辑页面**
/**
* 注意:
*
* 子组件引用和其他引用换行
* 基础组件用c+文件名命名
* 基础模块用m+文件名命名
* 页面子模块用p+文件名命名
* 如果没有用vuex或者redux 页面状态统一入口在父组件, 并加上注释
*/
import CWrap from 'components/wrap'
import MContainer from 'modules/container'
import PNotice from './notice'
 
export default {
  components: {
    CWrap, MContainer, PNotice
  },
 
  data () {
    return {
      // 用户信息
      user: {},
 
      // 获取本周以上数据
      weekScore: {},
 
      // 广播显示文案
      broadcastText: {}
    }
  }
}

css naming convention

 class 命名 用中杆, 这块得注意, 不能出现, a_b, aB, a_b-c, a_bC 这种奇怪的命名, 应该是 a-b, a-b-c, a-b-c-d
// bad
.a_b {}
.aB {}
.a_b_c {}
.a_bC {}
  
// good
.a {}
.a-b {}
.a-b-c {}

css namespace specifications and other techniques
less modular wording

  @joy-prefix-cls: ~'p-joy-new';
    .@{joy-prefix-cls}{
      &-wrapper{
        position: relative;
        width: 100%;
        height: 1772px;
        background: #ff949c;
        overflow: hidden;
      }
    }

The following code generation

.p-joy-new-wrapper {
  position: relative;
  width: 100%;
  height: 1772px;
  background: #ff949c;
  overflow: hidden;
}

vue modular use css

 <template>
  <div :class="`${classPrefix}-wapper`">
    模板内容
  </div>
 
</template>
 
const classPrefix = 'p-joy-new'
export default {
  data () {
    return {
      classPrefix
    }
  }
}

the introduction of less file aliases

@import '~common/less/var';
 
.bg {
  background-image: url('~asstes/images/banner/bg.png')
}

vue in reference to the image file path in assets

bad
<template>
  <div :class="`${classPrefix}-wapper`">
    <img :src="../../assets/images/banner/bg.png"/>
  </div>
</template>

good

<template>
  <div :class="`${classPrefix}-wapper`">
    <img :src="require('assets/images/banner/bg.png)"/>
  </div>
</template>

Method names defined

所有绑定事件类的方法统一前缀 on 例如:onOpen、onMessage
所有后端拉取数据的方法统一前缀 get 例如:getList、getStudentDetail、保存统一前缀save、更新统一前缀update、删除统一前缀delete
所有内部私有方法统一前缀 _ 例如:_compareTime、_isStudent

Avoid using "magic number"

    代码中所有关于状态, 类型相关的文字的值, 全部使用const声明, 如果是相对中等偏上项目, 声明一个文件, 如: constants/state.js

bad

// 这个0, 鬼知道是什么意思, 什么时候为0
// 即使项目中加了注释, 那么这个0, 如果在项目多个地方被用到, 就变得难以维护
// 比如: 第一: 状态更改了呢? 修改N个地方的代码, 第二: N个地方写同样的注释
if (this.state === 0) {
    ...
}

good

// 注意: 每个常量变量需要填写相关注释
// 停止直播
const STOP_LIVE = 0
// 开始直播
const START_LIVE = 1
 
 
// 这样后面不管别人看, 还是自己回过头看, 都能明白其中意义, 如果后面项目中状态有修改, 修改一处即可.
// 这就是可维护, 可扩展的小案例, 平时不管写业务代码还是通用框架, 多注意些小细节和反思, 就能有很多收获和提高
switch (LIVE_STATE) {
    case STOP_LIVE:
        ...
        break  
    case START_LIVE:
        ...
        break
    ...
}

Log specification
console.log debugging program can be used, but not after the on-line program, retains the last console.log useless, as console.log ( 'aaaaaaaaaaa'), console.log ( '-------- bbbb ') this will affect the development and debugging related secondary developer

   原则:

         1: 项目上线之后, 业务代码中console.log相关全部加注释

         2: 在通用库, 函数中, 可以保留部分console.log, 但是需要加入命名空间, 如:

console.log('[axios-service] someKey: ', url, params)
console.log('[inkeSdk] load: ', ...)
console.log('[loadingComponent] show: ', ...)

Details determine success or failure of a good senior programmer should follow the following specification

vue official website style guide: https://cn.vuejs.org/v2/style-guide/# classification rules

Block-level scope: let substituted var. var command variables exist to enhance the effectiveness, let the command does not have this problem.

Global Constants and thread-safe: in between let and const, recommended that priority use of const, especially in the global environment, should not be set variables, constants should only be set up.

String: static string Always use single quotes or back quotes, not double quotes. Dynamic strings using backticks.

Deconstruction assignment: When using arrays of member variable assignment, priority use destructuring assignment. If you are a member function of the parameters of the object, using deconstruction priority assignment.

Object: single defined objects, not the last member of a comma at the end. Multiline object definitions, a member of the end of last comma.

Try to static objects: Once defined, they are not free to add a new property. If you add attributes unavoidable, to use Object.assign method.

Array: Extended operator (...) copies array. Use Array.from method, array-like object into an array.

Function: immediately execute the function can be written in the form of an arrow function. Those who need to use the occasion of the function expression, as much as possible instead of using the arrow function. Because it is more concise, and bound this. Function arrow substituted Function.prototype.bind, should no longer self / _this / that bind this.

Module: import substituted require, the use of export substituted module.exports. If the module is only one output value, on the use of export default, if the module has multiple output values, do not use export default, export default and general export not both. If a default output function module, the first letter of the function name should be lowercase. If the default output of an object module, the first letter of the object name should be capitalized.

Analyzing the ternary conditional: dispensing or return statement ternary operator. Used in relatively simple case, avoid using a complex case.

Use strict like: === always use an accurate comparison operators, to avoid the process of determining, by the JavaScript problems casts caused.

contact

The new front-end technology exchange group of people called front-end technology, there Node.js / Vue.js / React.js / React- Native.js / micro-channel technology applet communication problems. Welcome! Group number: 426 334 209
Click on the link to join a group chat [front-end technology exchange group]: https://jq.qq.com/?_wv=1027&k=56akiog

Guess you like

Origin blog.csdn.net/qq_35715972/article/details/90515670