The complexity of modern software architecture requires collaborative development. How to effectively collaborate? For example, the formulation of traffic laws and regulations is ostensibly to restrict the right to drive, but in fact it is to protect the safety of the public. Imagine if there is no speed limit and no traffic light, who would dare to drive on the road. For software, proper specifications and standards do not eliminate the creativity and elegance of the content of the code, but rather limit excessive personalization, work together in a universally accepted and uniform way, improve collaboration efficiency, and reduce communication costs. Code flowing between the lines is the blood of the software system, quality improvement is as little as possible to step on the pit, put an end to the repetition of the pit, effectively improve the stability of the system, code out of the quality.

JS project specification

Naming conventions

Project named

Use lowercase letters and separate them with hyphens (-).

Is exemple: mall - management - systemCopy the code
Counter example: mall_management-system/mallManagementSystemCopy the code

The directory name

1, all use lowercase, delimited by hyphen, there is a complex structure, to use the plural naming method, abbreviations do not need to be plural

Example: scripts/styles/components/images/utils/layouts/demo-scripts/img/docCopy the code
Counterexample: script/style/demo_scripts/demoStyles/imgs/docsCopy the code

2. Component directory in Components of VUE’s project, named with Kebab-Case

Head: head-search/page-loading/Authorized/notice-iconCopy the code
Counter example: HeadSearch/PageLoadingCopy the code

3. All the directories in VUE’s project except the Components directory are also named kebab-Case

Example: page-one/shopping-car/user-managementCopy the code
Counter example: ShoppingCar/UserManagementCopy the code

JS, CSS, SCSS, HTML, PNG file name

Use lowercase letters and separate them with hyphens (-)

Example: render-dom.js/signup.css/index.html/company.logo.pngCopy the code
Counter example: renderdom.js/usermanagement.htmlCopy the code

Naming rigor

Code naming is strictly prohibited to use pinyin and English mixed way, not to allow the direct use of Chinese way. Explanation: Correct English spelling and grammar can make it easy for readers to understand and avoid ambiguity. Note that even pure pinyin naming should be avoided

Henan/BP is an international common name, which can be regarded as English.Copy the code
Counterexample: DaZhePromotion [discount] / getPingfenByName() [score] / int some variable = 3Copy the code

2. Put an end to completely non-standard abbreviations to avoid ambiguity:

Counterexample: AbstractClass "abbreviated" named AbsClass; Condition "abbreviations" are named condi, and such arbitrary abbreviations seriously reduce the readability of the code.Copy the code

HTML specification (Vue Template also applies)

HTML type

Text/HTML is recommended for HTML. Avoid XHTML. XHTML and its attributes, such as Application/XHTML + XML, have limited scope for application support and optimization in browsers.

Specified character encoding IE compatibility mode Specified character encoding DOCType UppercaseCopy the code
Is: <! DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta charset="UTF-8" /> <title>Page  title</title> </head> <body> <img src="images/company-logo.png" alt="Company" /> </body> </html>Copy the code

The indentation

1. Use 2 Spaces for indentation (one TAB)

2. Nested nodes should be indented.

Block comments

After each block, list, and table element, add a pair of HTML comments. The annotation format

Semantic tags

There are a lot of new semantic tags in HTML5, so use them first instead of div or P tags all over a page

<header></header> </footer>Copy the code
<div> <p></p>Copy the code

quotes

Use double quotes (” “) instead of single quotes (” ‘).

Is: ""

Example: "'

The CSS specification

named

In SCSS, variables, functions, blends, and placeholder are named with a humpCopy the code

The ID and class names always use names that reflect the purpose and purpose of the element, or other generic names, instead of figurative and obscure names

Word-break: break-word! Important; word-break: break-word! Important; } .red { color: red; }Copy the code
< span style = "box-sizing: border-box; } .important { color: red; }Copy the code

The selector

1. Avoid using tag names in CSS selectors. From the principle of separation of structure, performance and behavior, HTML tags should be avoided as far as possible in CSS, and tag names in CSS selectors will have potential problems.

2. Many front-end developers write selector chains without using direct subselectors (note the difference between direct subselectors and descendants). Sometimes this can lead to painful design issues and sometimes it can be performance draining. However, in any case, this is a very bad practice. If you don’t write generic selectors that need to match to the end of the DOM, you should always consider direct subselectors.

Mso-font-weight: 0pt; mso-font-weight: 0pt; mso-font-weight: 0pt; }Copy the code
Content >.title {font-size: 2rem; }Copy the code

Use abbreviated properties whenever possible

Border-top: none; border-top: none; font-family: palatino, georgia, serif; font-size: 100%; The line - height: 1.6; padding-bottom: 2em; padding-left: 1em; padding-right: 1em; padding-top: 0;Copy the code
Recommended: border-top: 0; Font: 100%/1.6 Palatino, Georgia, Serif; padding: 0 1em 2em;Copy the code

Each selector and property has an exclusive row

Button {width:100px; height:50px; color:#fff; background:#00a0e9; }Copy the code
Button {width:100px; height:50px; color:#fff; background:#00a0e9; }Copy the code

Omit the units after 0

Div {padding-bottom: 0px; margin: 0em; }Copy the code
Div {padding-bottom: 0; margin: 0; }Copy the code

Avoid ID selectors and global label selectors to prevent fouling global styles

Is not recommended:

#header {
  padding-bottom: 0px;
  margin: 0em;
}
Copy the code
Header {padding-bottom: 0px; margin: 0em; }Copy the code

LESS specification

Code organization

1. Place public less files in the style/less/common folder

Example: / / color. Less common. Less

2. Organize them in the following order

// @import // variable declaration // style declaration @import "mixins/size.less"; @default-text-color: #333; .page { width: 960px; margin: 0 auto; }Copy the code

Avoid too many nested levels

Limit the nesting depth to three levels. For nesting above level 4, a reassessment is given. This avoids overly detailed CSS selectors. Avoid large numbers of nested rules. Interrupt when readability is affected. It is recommended to avoid nesting rules with more than 20 lines

.main {.title {.name {color: # FFF; }}}Copy the code
.main-title {.name {color: # FFF; }}Copy the code

Javascript code

named

1. The name of the lowerCamelCase must not end with an underscore or a dollar sign

Example: _name/name_ / name$2) Use the lowerCamelCase style for method names, parameter names, member variables, and local variables.Copy the code
Example: localValue/getHttpMessage()/inputUserIdCopy the code

2, the name of the method must be a verb or a verb + noun

Example: saveShopCarData /openShopCarInfoDialog

Example: save/open/show/go

3. Hereby, add, delete, check and change, and use the following 5 words for details, and no other words (for the purpose of unifying each end).

add / update / delete / detail / get

Function method: Get Get /set add add /remove delete Create Create /destory Remove start start /stop Stop open Open /close Close Read Read /write Write Load Load /save Save Create Create /destroy destroy begin start /end End Backup backup /restore import Import /export Export Split split /merge Inject /extract extract Attach attach /detach bind /separate separate view /browse Edit edit /modify select select /mark copy /paste undo Redo /redo /redo /redo /redo /redo /redo /redo /redo Increase/Decrease play play /pause pause launch /run compile /execute Debug /trace Observe/Listen Build /publish input /output Encode /decode Decode encrypt /decrypt Decrypt Compress/Decompress Pack Unpack /unpack, parse /emit generates connect /disconnect Send Send /receive Receive download Download /upload Upload Refresh Refresh/Synchronize synchronize Update Update/Revert revert Lock Lock /unlock Unlock check out Check out /check in submit /commit push /pull expand /collapse begin /end start start/Finish Enter /exit Exit ABORT Abandon /quit Leave obsolete obsolete /depreciate old collect Collection/AggregateCopy the code

4, constant name all capitals, between the words separated by underscores, strive to complete and clear semantic expression, do not think the name is long.

Is exemple: MAX_STOCK_COUNT

Example: MAX_COUNT

Code format

1. Use 2 Spaces to indent

If (x < y) {x += 10; } else { x += 1; }Copy the code

2. Insert a blank line between different logic, different semantics, different business code to improve readability.

Note: In any case, it is not necessary to insert multiple blank lines to separate them.

string

Use single quotation marks (“”) instead of double quotation marks (“”). This is very useful in creating HTML strings:

Example: let STR = 'foo'; let testDiv = '<div id="test"></div>';Copy the code
Example: let STR = 'foo'; let testDiv = "<div id='test'></div>";Copy the code

Object statement

1. Create objects with literal values

Let user = {};

Example: let user = new Object();

2. Use literals instead of object constructors

Var user = {age: 0, name: 1, city: 3};Copy the code
Var user = new Object(); user.age = 0; user.name = 0; user.city = 0;Copy the code

Use the ES6, ES7

Must use ES6 first,ES7 added syntax sugar and functions. This will simplify your program and make your code more flexible and reusable.

You must force the use of ES6, ES7's new syntax, such as arrow functions, await/async, deconstruction, let, for... Of, etc.Copy the code

parentheses

The following keywords must be followed by braces (even if the block contains only one line) : if, else, for, while, do, switch, try, catch, finally, with.

If (condition) {doSomething(); }Copy the code
Counterexample: if (condition) doSomething();Copy the code

Undefined judgment

Never use undefined directly for variable judgment; Use typeof and the string ‘undefined’ to judge variables.

If (typeof person === 'undefined') {... }Copy the code
If (person === undefined) {... }Copy the code

Conditional judgment and loop up to three levels

Do not use conditions that can be resolved using ternary operators and logical operators, but remember not to write too long ternary operators. If there are more than 3 layers, please extract the function and write clear comments.

The transformation name for this

References to the context this can only be named using ‘self’

Careful with the console. The log

Use the log feature with caution in non-WebPack projects because of performance issues associated with heavy use of console.log

Vue Project specification

Vue Coding fundamentals

The VUE project specification is the official VUE specification(https://v3.cn.vuejs.org/style-guide/)All code adheres to the A specification on which the project is developed.

Please read the official Vue specification carefully, remember, this is the first step.

Component specifications

1. The component name is multiple words.

Component names should always be multiple words (at least 2) and be named in KebabCase format. This avoids conflicts with existing and future HTML elements, since all HTML element names are single-word.Copy the code
Export default {name: 'TodoItem' //... };Copy the code
Export default {name: 'Todo', //... } export default { name: 'todo-item', // ... }Copy the code

2. The component file name is pascal-case

Example: the components / | - my - component. VueCopy the code
Example: the components / | - myComponent. Vue | - myComponent. VueCopy the code

The base component file name starts with base, using full words instead of abbreviations.

Is exemple: components / | - base - button. The vue | - base - table. Vue | - base - icon. VueCopy the code
Example: the components / | - MyButton. Vue | - VueTable. Vue | - Icon. VueCopy the code

4. Child components that are tightly coupled to the parent should be named with the parent’s name as the prefix

Is exemple: components / | - todo - list. Vue | - todo list - - item. Vue | - todo list - item - button. Vue | - user - profile - options. Vue (full word)Copy the code
Example: the components / | - TodoList. Vue | - TodoItem. Vue | - TodoButton. Vue | - UProfOpts. Vue (use)Copy the code

5. When using components in the Template Template, use the PascalCase mode and use self-closing components.

Is: <! -- In single-file components, string templates, and JSX --> <MyComponent />< Row><table :column="data"/></Row>Copy the code
<my-component />< row><table :column="data"/></row>Copy the code

6. A component’s data must be a function

When using the data attribute in a component (anywhere except new Vue), its value must be a function that returns an object. If it is an object, the property values of the child components will affect each other.

Export default {data() {return {name: 'jack'}}}Copy the code
Export default {data: {name: 'jack'}}Copy the code

7. Prop definitions should be as detailed as possible

CamelCase must be used. The camelCase must be named. The type must be commented to indicate that it means either Required or defaultCopy the code
Status: {type: String, required: true, validator: function (value) { return [ 'succ', 'info', 'error' ].indexOf(value) ! UserLevel: {type: String, required: true}}, userLevel: {type: String, required: true}}Copy the code

Set the scope for the component style

<template> <button class=" BTN btn-close">X</button> </template> <! Btn-close {background-color: red; background-color: red; background-color: red; } </style>Copy the code
<template> <button class=" BTN btn-close">X</button> </template> <! <style>.btn-close {background-color: red; background-color: red; } </style>Copy the code

9. If there are many feature elements, take the initiative to wrap lines.

Is: < MyComponent foo = "a" bar = "b" baz = "c" foo = "a" bar = "b" baz = "c" foo = "a" bar = "b" baz = "c" / >Copy the code
For example: "MyComponent foo =" a "bar =" b "baz =" c "foo =" a "bar =" b "baz =" c "foo =" a "bar =" b "baz =" c "foo =" a "bar =" b "baz =" c "/ >Copy the code

Use simple expressions in templates

Component templates should contain only simple expressions, and complex expressions should be refactored to evaluate properties or methods. Complex expressions can make your templates less declarative. We should try to describe what should happen, not how to calculate that value. And calculating properties and methods makes the code reusable.

For example: <template> <p>{{normalizedFullName}}</p> </template> // A complex expression has been migrated to a computed attribute: {normalizedFullName: function () { return this.fullName.split(' ').map(function (word) { return word[0].toUpperCase() + word.slice(1) }).join(' ') } }Copy the code
Example:  <template> <p> {{ fullName.split(' ').map(function (word) { return word[0].toUpperCase() + word.slice(1) }).join(' ') }} </p> </template>Copy the code

Instructions are abbreviated

Directive recommendations all use abbreviations (: for v-bind:, @ for V-on:, and # for V-slot 🙂

<input @input="onInput" @focus="onFocus" />Copy the code
<input v-on:input="onInput" @focus="onFocus" /> <input v-on:input=" onFocus" @focus="onFocus" />Copy the code

Keep the label order consistent

Single-file components should always keep the label order as

Is: < the template >... </template> <script>... </script> <style>... </style>Copy the code
For example: "the template >... </template> <style>... </style> <script>... </script>Copy the code

You must set the key value for v-for

Select v-SHOW and V-IF

If you need to switch very frequently at runtime, use v-show; If conditions rarely change at run time, use V-if.

Script tag internal structure order

Components > props > data > computed > Watch > Filter > Hook functions (in the order that hook functions are executed) > Methods

Vue Router specification

1. Route parameters are used for page forward data transfer

Let id = '123'; this.$router.push({ name: 'userCenter', query: { id: id } });Copy the code

2. Use lazy route loading (lazy loading) mechanism

{path: '/uploadAttachment', name: 'uploadAttachment', meta: {title: '/uploadAttachment'}, component: () => import('@/view/components/uploadAttachment/index.vue') },Copy the code

3. Naming conventions of the Router

The naming convention of Path and childrenPoints adopts the Kebab-case naming convention (try to keep the directory structure of vUE files consistent, because the directory and file name are both Kebab-case, The name naming convention uses the KebabCase naming convention and is consistent with the Component name! (To preserve the keep-alive feature, which is cached by component name, the two must be highly consistent)Copy the code
Export const reload = [{path: '/reload', name: 'reload', component: Main, meta: {title: 'reload', icon: 'icon iconfont' }, children: [{ path: '/reload/smart-reload-list', name: 'SmartReloadList', meta: { title: 'SmartReload', childrenPoints: [{title: 'query ', name: 'smart-reload-search'}, {title:' perform reload', name: 'smart-reload-update'}, {title: 'smart-reload-update', name: 'smart-reload-result'}]}, component: () => import('@/views/reload/smart-reload/smart-reload-list.vue') }] } ];Copy the code

Vue Project directory specification

basis

All naming in the VUE project must be consistent with the backend naming. For example, privileges: backend privilege, front-end router, store, API, etc. must use the privielege word!

Use vue-CLI scaffolding

Use vue-CLI3 to initialize the project. The project name follows the naming convention above.

Directory description

The directory names follow the naming convention above, where components are named with uppercase hump and all other directories except components are named with Kebab-Case. SRC | - all the API interface API source directory | - static resource assets, Images, ICONS, styles, etc. | | - components common components - config configuration information | - constants constant information, Project all Enum, global constants | - directives such as the custom command | - filters filter, global tools | - datas analog data, temporary storage | - lib external reference plug-in to store and modify the file | - mock simulation interface, Temporary storage | plugins plugin, the global | - the router routing, Unified management | - store vuex, Unified management | - themes custom style theme | - views view directory | | - role role module name | | -- - | - role - the list. The vue role list page | | -- - | - role - the add. Vue role New page | | -- - | - role - update. Vue role updates page | | -- - | -- index. Less role module style | | -- - | - components role module common component folder | | - The employee the employee moduleCopy the code

1. API directory

Files and variables must be named the same as those on the back end. This directory corresponds to the back-end API interface, according to the back-end controller and API JS file. If the project is large, you can divide the molecular directory according to the business and keep it consistent with the back end. The method names in the API should be as semantically consistent as possible with the backend API URL. Add comments for each method in the API, consistent with the back-end Swagger documentation.Copy the code
Positive example: Back-end: URL: employeecontroller.java /employee/add /employee/delete/{id} /employee/update Front-end: AddEmployee: (data) => {return postAxios('/employee/add', data)}, // updateEmployee information (data) => {return postAxios('/employee/update', data)}, // deleteEmployee: (employeeId) => { return postAxios('/employee/delete/' + employeeId) },Copy the code

2. Assets directory

Assets are static resources where images, styles, ICONS and other static resources are stored. Static resource naming format for kebab - case | assets | - the ICONS | | - images | - background - color. PNG | | - upload - header. PNG | - stylesCopy the code

3. Components directory

This directory should be divided by component, named KebabCase, Component naming rules for KebabCase | components | - error - log | | - index. The vue | | - but less | - markdown - editor | | - index. The vue | | - index.js |-- kebab-caseCopy the code

4, Constants directory

This directory to store the project all constants, if the constants used in vue, please use the vue (https://www.npmjs.com/package/vue-enum) - enum plug-ins directory structure:  |constants |-- index.js |-- role.js |-- employee.jsCopy the code
Example: employee.js export const EMPLOYEE_STATUS = {NORMAL: {value: 1, desc: 'NORMAL'}, DISABLED: {value: 1, desc: DELETED: {value: 2, desc: 'delete'}}; Export const EMPLOYEE_ACCOUNT_TYPE = {QQ: {value: 1, desc: 'QQ login '}, WECHAT: {value: 2, desc: 'WECHAT login'}, WECHAT: {value: 2, desc: 'WECHAT login'}, WECHAT: {value: 2, desc: 'WECHAT login'}, WECHAT: {value: 2, desc: 'WECHAT login'}, WECHAT: {value: 3, desc, USERNAME: {value: 4, desc, password}}; export default { EMPLOYEE_STATUS, EMPLOYEE_ACCOUNT_TYPE };Copy the code

5. Router and Store directories

These two directories must split the business, can not be put in a JS file. The router tries to maintain the same structure according to the views. Store Splits JS files based on servicesCopy the code

6. Views directory

Name to be consistent with the back-end, router, API and other components in the component to use PascalCase rule | -- views view directory | | - role role module name | | | - role - the list. The vue role List page | | | - role - the add. Vue role new page | | | - role - update. Vue role updates page | | | -- index. Less role module style | | | - components Role module common component folder | | | | - role - the header. Vue role head component | | | | - role - modal. Vue role pop-up components | | - the employee the employee module | | - Behaviors - log activity log log module | | - code - the generator code generator moduleCopy the code

annotated

Tidy up where comments must be added

The js file in the API directory must be annotated. The state, mutation, and action files in the Store must be annotated. The template in the Vue file must be annotated. If the file is large add start end annotation vue file methods, each method must add annotation vue file data, unusual words should be annotatedCopy the code

other

1. Try not to manually operate the DOM

Because of the use of VUE framework, so in the project development, try to use vUE data-driven update DOM, as far as possible (not as a last resort) do not manually operate the DOM, including: adding, deleting and modifying DOM elements, as well as changing styles, adding events, etc.Copy the code

2. Delete useless code

Because you use code versioning tools such as Git/SVN, you must delete useless codes in time, such as debugging console statements and useless deprecated functional codes.Copy the code