Front-end development specification

General specification

Naming conventions

Named classification

  • CamelCase (also called small camel name, e.g. userInfo)
  • PascalCase (e.g. UserInfo)
  • Kebab-case (e.g. user-info)
  • Snake_case (underlined, e.g. user_info)

Variable naming

  • Naming method: small hump naming method
  • Naming conventions: The way a type + object is described or an attribute
// bad
var getTitle = "LoginTable"
Copy the code
// good
let tableTitle = "LoginTable"
Copy the code

The function name

  • Naming: small hump (constructors use large hump naming)
  • Naming rules: Prefixes are verbs
The function returns a Boolean value to determine whether an action can be performed. True: executable. False: cannot be executed has Checks whether a function containing a value returns a Boolean value. True: contains this value. False: does not contain this value is checks whether a value function returns a Boolean value. True: indicates a value; False: do not get a value for a value function returns a non-boolean value set set a value no return value, return success or return the chain objectCopy the code
Recommendation:
Function canRead(){return true; Function getName{return this.name} function getName{return this.name}Copy the code

Constant named

  • Naming method: all uppercase
  • Naming conventions: Use a combination of uppercase letters and underscores to separate words.
Recommendation:
const MAX_COUNT = 10;
const URL = 'http://test.host.com';
Copy the code

The name of the member of the class

  • Common properties and methods: same variable naming
  • Private properties and methods: prefix with underscore (_) followed by the same naming as public properties and methods
Recommendation:

functio

n Student(name) { var _name = name; // private member // public method this.getName = function () {return _name; } this.setName = function (value) {_name = value; } } var st = new Student('tom'); st.setName('jerry'); console.log(st.getName()); // => jerry: print the value of the _name private variableCopy the code

Annotation specifications

Single-line comments

  • A single line: //(double slash) leave a space between the comment text
  • Add comments after the code: //(double slash) leave a space between the code, and //(double slash) leave a space between the comment text.
  • Comment code: //(double slash) leave a space between the code.
Recommendation:
// calls a function <= 1) on a single line setTitle(); var maxCount = 10; // Set maximum <= 2) comment after code // setName(); // <= 3) comment the codeCopy the code

Multi-line comment (/ comment description /)

  • If the start (/*) and end (*/) are both on one line, single-line comments are recommended
  • If there are at least three lines of comment, the first line is /*, the last line is */, and the other lines are followed byStart, and comment the text withLeave a space.
Recommendation:
SetTitle () : setTitle(); setTitle() : setTitle();Copy the code

Function (method) comments

  • Function (method) comments are also a type of multi-line comment, but contain special comment requirements, as described in the JavaDoc specification
Grammar:
/** * function description * @ Keyword */Copy the code

Common comment keywords:

The annotation of grammar meaning The sample
@param @param Parameter name {Parameter Type} Description information Description Parameter information @param name {String} The incoming name
@return @return {Return type} Indicates the description Information describing the return value @return {Boolean} true: executable; False: Cannot be executed
@author @author Author information [Affiliated information: email address, date] Describes information about the author of this function @ the author zhang SAN 2015/07/21
@example @example Example code @example setTitle(‘ test ‘)

Where you need to add comments

Code comments are especially important in the later maintenance of a project, so we write component usage instructions for each component that is reused and method instructions for each method in the component.

You must add a comment when:
    1. Usage instructions for common components
    1. Description of important functions or classes in a component
    1. Complex business logic processing instructions
    1. Special case code processing instructions, for the code for special purpose variables, the existence of critical values, hacks used in the function, the use of a certain algorithm or ideas need to be commented description
    1. Multiple if statements

Vue specification

Vue project specification

Structured Specification (Webpack)

├─ index.html entry Page ├─ Favicon.ico page ICONS ├─.Babelrc Rules ├─.EditorConfig Editor Configuration ├─.EsLintignore EsLint Ignore Rules ├─ .esLintrc.js EsLint Rule ├─.gitignore Git Ignore Rule ├─ Build Build Script directory │ ├─ build-server.js Run local Build Server │ ├─ ├─ Dev-client.js Dev Server Heavy Loading Script, │ ├─ Dev-client.js Dev Server Heavy Loading Script │ ├─ Webpack.base.conf. Js Basic configuration │ ├─ webpack.base.conf. Js Basic configuration │ ├─ dev-server.js ├ ─ ├ ─ ├ ─ sci-imp (sci-imp, sci-imp, sci-imp, sci-imp, sci-imp, sci-imp, sci-imp, sci-imp ├─ config project │ ├─ Dev.env.js Environment variables │ ├─ index.js project Configuration file │ ├─ prod.env.js │ ├─ ├─ ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ SRC project source directory │ ├─ main.js ├─ app.vue Root Component │ ├── Public Component directory │ │ ├─ ├─ SRC project source directory │ ├─ main.js ├─ app.vue root component │ ├── public component directory │ │ ├─ ├─ SRC project source directory │ ├─ main.js Componentitem. vue │ ├─ Assets Static Resources Directory, The resources here will be wabpack build │ │ ├ ─ ─ the CSS style of public file directory │ │ ├ ─ ─ js public js file directory (e.g., help) │ │ └ ─ ─ img image storage directory | | ─ ─ lib external reference plug-in to store and modify the file | | - datas │ ├─ ├─ apis │ ├─ apis │ ├─ apis │ ├─ apis │ ├─ apis │ ├─ ├─ ├─ ├─ exercises, Unified management │ │ └ ─ ─ index. Js │ └ ─ ─ views view module name │ ├ ─ ─ the view module - module view | └ ─ ─ index. The vue view module's main page │ ├ ─ ─ hello.html vue │ └ ─ ─ Notfound. Vue ├─ Static Pure static resources, not built by WABPack. └ ─ ─ the test test file directory (2 e) unit&e └ ─ ─ unit unit test ├ ─ ─ index. The js script entrance ├ ─ ─ karma. Conf., js karma configuration file └ ─ ─ specs sheet test case directory └ ─ ─ Hello.spec.jsCopy the code

Directory, file, and component naming conventions

1. The directory

The directory uses the kebab-case style

2. Files under views
  • Js class files use PascalCase, such as userinfo.js
  • Other resource files use the kebab-case style, such as user-detail.js, user-detail. CSS, and user-avatar.png
3. Component files
  • Naming follows the PascalCase convention.

Component file names are PascalCase except index.vue. The reason is that when importing a component, its variables are usually in PascalCase format to distinguish them from normal variables. The component file name is the same as the variable name for easy correspondence.

import UserBook from './user/UserBook'
Copy the code
  • Component names should always be multiple words, except for the root component App

HTML elements are single-word (e.g

  • Component usage follows the Kebab-case convention

Using components in a page should be closed and separated by short lines, as in:

<user-book></user-book>
Copy the code

Vue development specification

Vue file structure

The basic structure

Order: template -> script -> style. Try not to have more than 200 lines for a component, and try to split the page into sub-components when it contains individual parts.

<template> <div>... </div> </template> <script> export default { components: {}, data() { return {}; }, created(){}, methods: {}, }; </script> <! <style lang=" SCSS "scoped>... </style>Copy the code
  • Component/instance option order
Name (global reference) Components (template dependent) Directives... filters ... Mixins (composite) props (interface) Data (local state attributes) computed... Watch (callback) created (lifecycle function) mounted... Methods (Instance Attributes)Copy the code

Vue Router Path specification

The router path is in kebab-case format.

Words underlined (e.g. /user_info) or camelCase (e.g. /userInfo) are treated as one word and search engines cannot distinguish semantics.

// bad {path: '/user_info', // user_info as a word Name: 'UserInfo', Component: UserInfo, meta: {title: '- user ', desc: // good {path: '/user-info', // good {path: '/user-info', // Good {path: '/user-info', // Good {path: '/user-info', // Good {path: '/user-info', // Good {path: '/user-info', // Good {path: '/user-info', // '- user ', desc:'}},Copy the code

Component development specification

1. Register components

When registering components, use all PascalCase formats.

import UserBook from './user/UserBook'
Copy the code
2. Props naming convention

When declaring prop, it should always be named camelCase, and kebab-case should always be used in templates

<! -- bad --> <welcome-message greetingText="hi"></welcome-message> <script> props: { 'greeting-text': String } </script> <! -- good --> <welcome-message greeting-text="hi"></welcome-message> <script> props: { greetingText: String; } </script>Copy the code
  • Prop definitions should be as detailed as possible
  1. Atomic component props
  2. Provide default values
  3. Verify the type using the type attribute
// Bad this is only acceptable for prototyping: ['status'] // Good props: {status: {type: String, required: true, validator: function (value) { return [ 'syncing', 'synced', 'version-conflict', 'error' ].indexOf(value) ! == -1}}}Copy the code
3. Methods naming conventions
  • Camel name, use a verb or verb + noun form
// Good jumpPage, openCarInfoDialogCopy the code
  • Request data methods, ending with data
//bad takeData, confirmData, getList, postForm // good getListData, postFormDataCopy the code
  • Try to start with common words (set, get, go, can, has, is)
Function methods:

Get Gets /set Settings,

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 restore import import /export export split merge inject /extract Attach /detach/bind /separate, view /browse edit /modify, select /mark copy copy /paste paste, Undo undo /redo insert insert /delete remove add add /append add clean clean /clear clear index index sort find search search Increase /decrease play play /pause launch /run compile /execute Debug debug /trace trace observe /listen Build /publish input /output Encode /decode Encrypt /decrypt compress /decompress Pack Pack /unpack Parse /emit generate connect /disconnect/send /receive Download /upload Update /revert/lock /unlock check out /check in Submit /commit push /pull expand /collapse begin /end, start /finish Enter /exit Abort discard /quit Leave obsolete /depreciate discard, collect /aggregateCopy the code
4. HTML element specification for multiple attributes

If multiple feature elements occupy too long a line, they should be written in multiple lines, one for each feature. (Enhanced and easier to read)

<! -- bad --> <img src="https://vuejs.org/images/logo.png" alt="Vue Logo"> <my-component foo="fooattribute" bar="barattribute" baz="bazattribute"></my-component> <! -- good --> <img src="https://vuejs.org/images/logo.png" alt="Vue Logo" > <my-component foo="fooattribute" bar="barattribute" baz="bazattribute" > </my-component>Copy the code
5. The order of element attributes

Native attributes come first, directives come later

-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-textCopy the code
6. Instruction specification
  • Instructions with abbreviations shall be abbreviated
// bad
v-bind:code="code"
v-on:click="getUserData"

// good
:code="code"
@click="getUserData"
Copy the code
  • The V-for loop must have a key attribute, which must be unique throughout the for loop
<! -- bad --> <ul> <li v-for="todo in todos"> {{ todo.text }} </li> </ul> <! -- good --> <ul> <li v-for="todo in todos" :key="todo.id"> {{ todo.text }} </li> </ul>Copy the code
  • To avoid the need for v-if and V-for to be used on the same element (performance issues), there are two solutions:
  1. Replace the data with a calculated property that returns the filtered list
<! -- bad --> <ul> <li v-for="user in users" v-if="user.isActive" :key="user.id"> {{ user.name }} </li> </ul> <! -- good --> <ul> <li v-for="user in activeUsers" :key="user.id"> {{ user.name }} </li> </ul> <script> computed: { activeUsers: function () { return this.users.filter(function (user) { return user.isActive }) } } </script>Copy the code
  1. Move v-if to container elements (such as ul, OL)
<! -- bad --> <ul> <li v-for="user in users" v-if="shouldShowUsers" :key="user.id"> {{ user.name }} </li> </ul> <! -- good --> <ul v-if="shouldShowUsers"> <li v-for="user in users" :key="user.id"> {{ user.name }} </li> </ul>Copy the code
other
  1. To avoid this. $parent
  2. Debug information Console.log () is deleted after being used
  3. Except for ternary operations, if,else, etc
  4. Semicolons may or may not be added at the end of a line. They should be in the same style, but are not recommended. The function of semicolons does not affect modern ES scripts. If you do not understand the function of semicolons, the pit will be entered. Code without semicolons is much cleaner. Most Vue projects have removed semicolons.

// bad

if (true)
  alert(name);
console.log(name);

// bad
if (true)
alert(name);
console.log(name);

// good
if (true) {
  alert(name)
}
console.log(name)
Copy the code

HTML specification

The script to load

  • Compatible with older browsers (IE9-) :

The script reference is written before the body closing tag with the async property. This does not load scripts asynchronously in older browsers, but it only blocks DOM parsing before the body tag ends, which greatly reduces its blocking impact.

  • In modern browsers:

The script is loaded only when the DOM parser finds the script tag at the end of the body, and the load is asynchronous and does not block CSSOM (but its execution still happens after CSSOM). Therefore, compatible with all browsers, it is recommended that:

<html> <head> <link rel="stylesheet" href="main.css"> </head> <body> <! -- body goes here --> <script src="main.js" async></script> </body> </html>Copy the code

Copy code is only compatible with modern browsers, if:

<html> <head> <link rel="stylesheet" href="main.css"> <script src="main.js" async></script> </head> <body> <! -- body goes here --> </body> </html>Copy the code

semantic

Semantically means using an element according to its original meaning when it was created. Using the right tags to express the right content is also good for SEO.

Use nav, header, article, section and other semantic tags properly, not all divs.

The Alt label is not empty

The Alt attribute of the tag specifies the alternative text to replace what the image displays in the browser if the image cannot be displayed or if the user disables it. The Alt attribute can provide alternative information for the image, assuming that the user cannot view the image for one of the following reasons:

  • Speed is too slow
  • Error in SRC attribute
  • Disable images in browser
  • The user uses a screen reader

From an SEO perspective, the browser crawler can’t crawl the content of the image, so we need text to tell the crawler what the content of the image is

Separation of structure, performance and behavior

  • Try to include only structured HTML in your documents and templates;
  • Move all the presentation code into the stylesheet;
  • Move all the actions into the script.

HTML is all about content

  • HTML only displays display content information
  • Instead of introducing specific HTML constructs to solve visual design problems, consider using pseudo-elements :before, :after
  • Don’t think of the IMG element as a visual design element
  • Styling problems should be solved using CSS
<! -- bad --> <! -- We should not introduce an additional element just to solve a design problem --> <span class="text-box"> <span class="square"></span> See the square next to me? </span> CSS code:.text-box >. Square {display: inline-block; width: 1rem; height: 1rem; background-color: red; } <! -- good --> <! -- That's clean markup! --> <span class="text-box"> See the square next to me? </span> CSS code: /* We use a :before pseudo element to solve the design problem of placing a colored square in front of the text content */ .text-box:before { content: ""; display: inline-block; width: 1rem; height: 1rem; background-color: red; }Copy the code

JS specification

General specification

Use strict equal ===

Always use the === exact comparison operator to avoid the hassle of JavaScript casts in the judgment process.

This keyword

Use this only in object constructors, methods, and in specified closures. The semantics of this are often misleading. It points sometimes to a global object (most of the time), sometimes to the caller’s domain (in eval), sometimes to a node in the DOM tree (when bound to an HTML property with event handling), sometimes to a newly created object (in the constructor), Sometimes it refers to other objects (if the function is executed and called by call() and apply()). Because it’s so easy to get it wrong, limit its use scenarios:

  • In the constructor
  • In the methods of the object (including the closure created therefrom)

Ternary operator

Allocates or returns statements with ternary operators. Use in simple situations and avoid complex ones.

// bad
if(x === 10) {
  return 'valid';
} else {
  return 'invalid';
}

// good
return x === 10 ? 'valid' : 'invalid'
Copy the code

Do not use the eval() function

As literal as eval is, devil, using eval() is a security risk. The eval() function returns an arbitrary string, treated as js code.

Use the ES6 coding specification

  • Let is used to define variables and const is used to define constants
  • Static strings use single or backquotation marks, and dynamic strings use backquotation marks // bad
const a = 'foobar';
const b = 'foo' + a + 'bar';

// good
const a = 'foobar';
const b = `foo${a}bar`;
const c = 'foobar';
Copy the code
  • Deconstruction assignment
Const arr = [1, 2, 3, 4]; // bad const first = arr[0]; const second = arr[1]; // good const [first, second] = arr; // bad function getFullName(user) {const firstName = user.firstname; const lastName = user.lastName; } // good function getFullName(obj) { const { firstName, lastName } = obj; } // best function getFullName({ firstName, lastName }) {}Copy the code
  • Using extension operators (…) Copy the array. const items = [1, 2, 3, 4, 5];
// bad
const itemsCopy = items;
// good
const itemsCopy = [...items];
Copy the code
  • Arrow function

When functional expressions are required, use arrow functions instead. Because it’s cleaner and binds this//

bad const self = this; const boundMethod = function(... params) { return method.apply(self, params); }; // good const boundMethod = (... params) => method.apply(this, params);Copy the code

The CSS specification

Use ids wisely

In general, ID should not be used for styles, and ID is heavily weighted, so instead of using ID to solve style problems, use class

Avoid label names in CSS selectors

In terms of separating structure, presentation, and behavior, HTML tags should be avoided in CSS, and the presence of tag names in CSS selectors is potentially problematic.

Use direct child selectors

Using descendant selectors can often lead to design problems and performance losses, which is a bad practice, and direct child selectors should always be considered

/* bad */
.content .title {
  font-size: 2rem;
}
/* good */
.content > .title {
  font-size: 2rem;
}
Copy the code

Use abbreviated attributes whenever possible

It is useful for code efficiency and readability to use abbreviations whenever possible, such as the font attribute.

/* bad */ .user-box { border-top-style: 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; } /* good */ .user-box { border-top: 0; Font: 100%/1.6 Palatino, Georgia, Serif; padding: 0 1em 2em; }Copy the code

Zero is not followed by a unit

/* bad */
.user-box {
    padding-bottom: 0px;
    margin: 0em;
}

/* good */
.user-box {
    padding-bottom: 0;
    margin: 0;
}
Copy the code

Attribute format

  • To ensure consistency and extensibility, each declaration should end with a semicolon, and each declaration should end with a line break.
  • Use a space after the colon of the attribute name. For reasons of consistency,
  • Always use a space between attribute and value (but no space between attribute and colon).
  • Always use a new line for each selector and property declaration.
  • Property selectors or property values are enclosed in double quotes (“”) instead of single quotes (“”).

Attribute order

As a best practice, sort by grouping and importance. Specifically, from the outside in, from the relationship between the elements and the outside, whether it will affect the external layout, to margins, margins, etc.

  1. Layout dependencies (display, position, float, overflow, clear) are important because the layout of an element affects neighboring elements and may even detach itself from the original document flow.
  2. Box model correlation (width, height, margin, padding)
  3. Appearance (color, background, border, box-shadow)
  4. Font size, font-family, text-align, text-transform
  5. Other (cursor, z – index)
/* bad */ .box { font-family: 'Arial', sans-serif; border: 3px solid #ddd; left: 30%; position: absolute; text-transform: uppercase; background-color: #eee; right: 30%; isplay: block; The font - size: 1.5 rem; overflow: hidden; padding: 1em; margin: 1em; } /* good */ .box { display: block; position: absolute; left: 30%; right: 30%; overflow: hidden; margin: 1em; padding: 1em; background-color: #eee; border: 3px solid #ddd; font-family: 'Arial', sans-serif; The font - size: 1.5 rem; text-transform: uppercase; }Copy the code