See the personal blog: shengchangwei. Making. IO/js – style
Programs are written for people to read, and only occasionally for computers to execute. — Donald Knuth
The following code styles are for reference only. There is no clear stipulation about which writing style is good and which writing style is not good. The unity of code styles aims to improve the readability of the code.
A, HTML
1. Basic principles
html
(Structure),css
(Style),js
(Style) separation- Tags are semantic
- 2 space characters for an indent level, set typing
Tab
Key to insert 2 Spaces - Label names are all lowercase letters,
vue
Component names must be lowercase - The label must be closed and self-closed (
self-closing
) tag, no need to close (for example:img
input
br
hr
Etc.); - Don’t use
id
Selector,class
Use a hyphen to name multiple words-
The connection - Properties appear in a specific order to ensure readability,
id
,class
,name
,src
,for
,type
,href
,title
andalt
- Disallows inline elements to nest block-level elements
<! -- Add comment content -->
An exclusive line
2, class naming rules
- Chinese cannot appear
- Start with a letter. Do not use other formats
- Naming by name requires a standard, meaningful, and quick understanding of the specific meaning of the label
The form that collects long ago, specific source oneself remember not clearly, if have tort, can contact with oneself, thank
named | instructions |
---|---|
.wrapper | The periphery of the page controls the overall layout width |
The container or the content | Container, for the outermost layer |
.layout | layout |
.head, .header | The header section |
.foot, .footer | The footer section |
.nav | The main navigation |
.subnav | Secondary navigation |
.menu | The menu |
.submenu | Sub menu |
.sideBar | The sidebar |
.sidebar_a, .sidebar_b | Left column or right column |
.main | Page body |
.tag | The label |
.msg .message | Prompt information |
.tips | tip |
.vote | vote |
.friendlink | Friendship connection |
.title | The title |
.summary | Abstract |
.loginbar | Log on to the |
.searchInput | Search input box |
.hot | Hot hot |
.search | search |
.searchBar | Article search. |
.search_results | The search results |
.copyright | Copyright information |
.branding | The trademark |
.logo | Website LOGO |
.siteinfo | Website information |
.siteinfoLegal | Legal notices |
.siteinfoCredits | credibility |
.joinus | Join us |
.partner | partners |
.service | service |
.regsiter | registered |
arr/arrow | The arrow |
.guild | guide |
.sitemap | Site map |
.list | The list of |
.homepage | Home page |
.subpage | Secondary page face page |
.tool, .toolbar | The toolbar |
.drop | The drop-down |
.dorpmenu | The drop-down menu |
.status | state |
.scroll | rolling |
.tab | TAB |
.left .right .center | Left, center and right |
.news | news |
.download | download |
.banner | Advertising bar (Top advertising bar) |
Second, the CSS
1. Ground rules
- Use 2 Spaces for indentation
- Don’t use
id
Selector,class
Use a hyphen to name multiple words-
The connection - Open curly brace
{
Preceded by a space, close curly brace}
An exclusive line - The colon in the attribute
:
Followed by a space, followed by no space
2, comments,
- It is recommended to use line comments (in
Sass
Is in the//
) instead of block comments. - It is recommended that comments be on a single line. Avoid end-of-line comments.
3, border
Use 0 instead of None when defining a borderless style
// bad
.nav {
border: none;
}
// good
.nav {
border: 0;
}
Copy the code
4, Sass
- use
.scss
Syntax, do not use.sass
The original syntax. - Variable names are humped
$borderLine
Three, JavaScript,
1. Basic formatting
1.1 Indent level
Two Spaces is an indentation level. Insert two Spaces when you press Tab
1.2 Statement End
The statement ends with a semicolon
1.3 Line Length
A single line of code contains a maximum of 80 characters
Vscode configuration is as follows:
{
"editor.wordWrap": "wordWrapColumn"."editor.wordWrapColumn": 80
}
Copy the code
1.4 a newline
When a line reaches the maximum number of characters, you need to manually split the line into two lines. Usually we wrap the operator and add two levels of indentation on the next line.
1.5 named
The naming length should be as short as possible, and to get to the point where the variable name reflects the data type of the value as much as possible. For example, naming count, length, and size indicates that the data type is a number, while naming name, title, and message indicates that the data type is a string. But variables with single character names such as I, j, and k are commonly used in loops. Using names that reflect data types makes your code easy to read by others and yourself.
Do not name properties and methods with an underscore _ ending or beginning.
1.5.1 Variables and Functions
Variables: Follow camel case nomenclature, and the name prefix should be a noun.
let count = 0;
let myName = 'sheng';
let visible = true;
Copy the code
Function: follow camel case nomenclature, and the name prefix should be a verb.
function getName() {};
function setName() {};
Copy the code
Common conventions for using verbs
The verb | meaning |
---|---|
can | The function returns a Boolean value |
has | The function returns a Boolean value |
is | The function returns a Boolean value |
get | The function returns a non-boolean value |
set | The function is used to hold a value |
1.5.2 constants
Constants: Constants must be defined using const
const count = 10;
const url = 'http://baidu.com';
Copy the code
1.5.3 function
- In the control statement (
if
、while
Put a space before the parentheses. In function calls and declarations, do not prefix function argument lists with Spaces.
// bad
function getName () {
return userName;
}
// good
function getName() {
return userName;
}
Copy the code
- Do not save a reference to this. Use the arrow function or Function#bind.
// bad
function getName() {
const self = this;
return function() {
console.log(self); }}// bad
function getName() {
const that = this;
return function() {
console.log(that);
};
}
// good
function getName() {
return (a)= > {
console.log(this);
};
}
Copy the code
1.5.3 Constructors
In JavaScript, constructors are simply functions preceded by the new operator used to create objects
Constructor: Follow the Pascal Case nomenclature
function Person(name) {
this.name = name
}
Copy the code
2, comments,
2.1 Single-line comments
- The indentation level remains the same as the next line of code
- A double slash is followed by a space to keep the comment text offset
- Comments at the end of a line of code, with an indentation between the end of the code and the comment, should be moved above the current line of code if the maximum character limit for a single line is exceeded.
// bad
// This is a Person constructor
function Person(name) {
this.name = name
}
// good
// This is a Person constructor
function Person(name) {
this.name = name
}
// bad
const MAX_COUNT = 10; // This is a constant
// good
const MAX_COUNT = 10; // This is a constant
Copy the code
2.2 Multi-line comments
// There is no space before the bad comment
if (condition) {
/** * if the code is executed at this point */
console.log('Hello world! ');
}
// bad has no space after the asterisk
if (condition) {
/** * if the code is executed at this point */
console.log('Hello world! ');
}
// bad bad indentation
if (condition) {
/** * if the code is executed at this point */
console.log('Hello world! ');
}
// good
if (condition) {
/** * if the code is executed at this point */
console.log('Hello world! ');
}
Copy the code
3. Statements and expressions
3.1 All block statements should use curly braces, including
if
for
while
do... while...
try... catch... finally
// bad
if (condition) console.log('Hello world! ');
// good
if (condition) {
console.log('Hello world! ');
}
Copy the code
3.2 Add Spaces before and after statements and expressions
// there is no space before or after bad
if(condition){
doSomething();
}else{
doElseSomething();
}
// good
if (condition) {
doSomething();
} else {
doElseSomething();
}
Copy the code
3.2 switch statement
// bad
switch (condition) {
case 0:
console.log(0);
break;
case 1:
console.log(1);
break;
default:
console.log('default');
}
// good
switch (condition) {
case 0:
console.log(0);
break;
case 1:
console.log(1);
break;
default:
console.log('default');
}
Copy the code
3.3 with statement
Disallow the with statement
3.4 a for loop
Avoid using continue whenever possible
// bad
for (let i = 0; i < array.length; i++) {
if (i === 2) {
continue; // Skip this iteration
};
doSomething();
}
// good
for (let i = 0; i < array.length; i++) {
if(i ! = =2) {
doSomething();
};
}
Copy the code
3.5 the for – in circulation
- You must use the
hasOwnProperty()
Methods forfor-in
Loop through the instance attributes, unless you want to find the prototype chain - It is prohibited to use
for-in
Through the array
// bad
for (let k in obj) {
console.log(obj[k]);
}
// good
for (let k in obj) {
if (obj.hasOwnProperty(k)) {
console.log(obj[k]); }}Copy the code
4, summary
4.1 object
- Create objects using literals
// bad
const obj = new Object(a);// good
const obj = {};
Copy the code
- When creating objects with dynamic property names, use property names that can be computed
function getKey(k) {
return `a key name ${k}` ;
};
// bad
const obj = {
id: 1.name: 'sheng'
};
obj[getKey('hidden')] = true;
// good
const obj = {
id: 1.name: 'sheng',
[getKey('hidden')] = true
}
Copy the code
- Use shorthand for object methods
// bad
const obj = {
name: 'sheng'.setName: function(name) {
returnobj.name + name; }}// good
const obj = {
name: 'sheng',
setName(name) {
returnobj.name + name; }}Copy the code
4.2 an array
- Create arrays using literals
// bad
const arr = new Array(a);// good
const arr = [];
Copy the code
- Use extension operators
.
Copy the array
// bad
let arr = [1.2.3];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr[i] = arr[i];
};
// good
const newArry = [...arr];
Copy the code
4.3 deconstruction
- Use deconstruction to access and use multi-attribute objects
// bad
function getUserInfo(user) {
const name = user.name;
const age = user.age;
}
// good
function getUserInfo(user) {
const {
name,
name
} = user;
}
Copy the code
- Use destruct assignment for arrays
const arr = [1.2.3.4];
// bad
const num0 = arr[0];
const num1 = arr[1];
// good
const [num0, num1] = arr;
Copy the code
4.4 the string
- Strings use single quotes
// bad
const name = "sheng";
// good
const name = 'sheng';
Copy the code
4.5 Using template Strings instead of string concatenation
// bad
window.open(configService.domain + '/exportFile');
// good
window.open( `${configService.domain}/exportFile` );
Copy the code
4.5 the function
- Use function declarations instead of function expressions
// bad
const getName = function() {};// good
function getName() {}Copy the code
- A function that is called immediately
((a)= > {
console.log('Hello world! '); }) ();Copy the code
- Don’t use arguments. Rest syntax can be used
.
alternative
// bad
function getName () {
const args = Array.prototype.slice.call(arguments);
return args.join(' ')}// good
function getName(. args) {
return args.join(' ');
}
Copy the code
4.6 Arrow Function
let arr = [1.2.3];
// bad
arr.map(function(x) {
return x + 1;
})
// good
arr.map(x= > {
return x + 1;
})
// good
arr.map(x= > x + 1);
Copy the code
4.7 the constructor
- use
class
, avoid usingprototype
// bad
function User(user) {
this.userName = user.name
}
User.prototype.getName = function() {
return this.userName;
}
// good
class User {
constructor(user) {
this.userNmae = user.name
}
getName() {
return this.userName; }}Copy the code
4.8 module
- To use (
import
/export
) instead of other modular systems, except in special circumstances
// bad
const data = require('./data.js');
module.exports = data;
// good
import data from './data.js';
export default data;
Copy the code
4.9 Comparing operators and equals signs
- Preferred to use
= = =
和! = =
Rather than= =
和! =
; - Conditional expressions for example
if
Statement through abstract methodsToBoolean
Force their expressions to be evaluated and always follow the following rules:- The object is evaluated to
true
undefined
Be calculated asfalse
null
Be calculated asfalse
boolean
Be calculated asboolean
- If the number is +0, -0, or
NaN
Be calculated asfalse
, or fortrue
- String if it is an empty string
' '
Be calculated asfalse
, or fortrue
- The object is evaluated to
// bad
if(name ! = =' ') {}// good
if (name) {
}
// bad
if (arr.length > 0) {}// good
if (arr.length) {
}
Copy the code
4.10 the blank space
- Use Spaces to separate the operators
// bad
const y=x+1
// good
const y = x + 1;
Copy the code
4.11 the semicolon
- Use a semicolon
// bad
function getName() {}
// good
function getName() {};
Copy the code
4.12 Type Conversion
// bad
const str = 0 + ' ';
// good
const str = String(0);
// bad
const num = +'4';
// good
const num = Number('4');
// bad
const b = new Boolean(0);
// good
const b = Boolean(0);
// good
const b = !!0;
Copy the code
Iv. Code style for VUE
This is for individual teams only, but you can also make suggestions and learn together.
1. Project Structure (VUE-CLI 3.0)
The following example project structure is suitable for the current stage of service development. In the later stage, the project structure can be added or deleted based on the service scenario
The SRC folder
| | - API interface (request folder) - rain - search | | - rian - search. API. Js (at the rear end of the corresponding page request) | -- - water - info | | - use - water - manage. API. Js | | - use - water - search. API. Js | - assets | - components (global common component) | - environments (environment configuration, Including the development environment and production environment) | -- environment. Dev. Js | -- environment. Prod. Js | - services | -- auth. Service. Js correlation function (package and user authorization) | -- - Config. Service. Js (export development environment and generate environment configuration items) | -- request. Service. Js (encapsulated axios, as well as some requests to intercept) | - styles element | -- - UI. SCSS | - Index. The SCSS | - utils (global common method) | - views | - errorPage | | - 404. The vue | | - 401. The vue | - home | - rain - search (currently only primary navigation menu) | | - components (only used to store the current page components) | | - index. The vue (the current directory entry page, Are named index. Vue) | - water - info (the current navigation has a second level menu) | | - use - water - manage | | - components | | - index. The vue | | - use - water - search | |-- components | |-- index.vue |-- APP.vue |-- main.js |-- router.js |-- store.jsCopy the code
- Page files use different words
-
Hyphen naming
2. API folder
api
Folder to create folder name withviews
The pages in the folder are the same, facilitating the back-end interface corresponding to the quick page- The name of the exported file is
Api
As a suffix, the function of a file can be specified as follows:
import request from '.. /services/request.service';
const useWaterSearchApi = {
getUserResources() {
return request.get('/mock/getUserResources.json'); }};export default useWaterSearchApi; // use Api as the suffix
Copy the code
- The name of the imported interface must be the same as the name of the exported interface
3. Assets folder
assets
The folder stores three main folders, respectivelyfonts
(font),images
(Picture),js
(External imported JS file)
4
- The routing
path
andname
Value is the hump name of the corresponding page file, which is helpful to find the corresponding page through the address bar
- The primary and secondary menus of the page are nested
children
writing - Adding routing Objects
meta
Object,meta
Object has two properties, onetitle
Is the name that the current navigation will display on the page, and the other ishidden
Used to determine whether to display on the page
The sample
new Router({
routes: [{path: '/'.component: Home,
redirect: '/rainSearch'.meta: { title: 'Rainfall Enquiry' },
children: [{path: 'rainSearch'.name: 'rainSearch'.component: (a)= > import('@/views/rain-search/index.vue'),
meta: { title: 'Rainfall Enquiry'}}]}, {path: '/waterInfo'.component: Home,
redirect: '/waterInfo/useWaterManage'.meta: { title: 'Rainfall information' },
children: [{path: 'useWaterManage'.name: 'useWaterManage'.component: (a)= > import('@/views/water-info/use-water-manage/index.vue'),
meta: { title: 'Water Management'}}, {path: 'useWaterSearch'.name: 'useWaterSearch'.component: (a)= > import('@/views/water-info/use-water-search/index.vue'),
meta: { title: 'Water Enquiry'}}]}, {path: The '*'.meta: { title: '404'.hidden: true },
component: (a)= > import('@/views/errorPage/404')}});Copy the code
5. Vue files
- The file structure is generally sound
template
,js
,css
The order, - The order of components, properties/states, life cycles, methods,
- The order of the lifecycle methods is in order of execution
name
Named after the file name
<template>
</template>
<script>
export default {
name: 'use-water-search'
components: {},
props: {},
filters: {},
data () {
return {}
},
computed: {},
watch() {},
beforeCreate () {},
created () {},
beforeMount () {},
mounted () {},
beforeUpdate () {},
updated () {},
beforeDestroy () {},
destroyed () {},
methods: {},
}
</script>
<style lang="scss" scoped>
</style>
Copy the code
- Do not omit all introduced file suffixes, such as component suffixes
.vue
,.js
- On the imported file
.vue
,.js
To group,.vue
Put it in the front,.js
Followed by
import sideBar from './components/side-bar/side-bar.vue';
import navBar from './components/nav-bar/nav-bar.vue';
import useWaterSearchApi from '@/api/water-info/use-water-search.js'
Copy the code
css
Have to addscoped
attribute- Attributes appear in a specific order and are wrapped to ensure readability, as follows
<el-pagination ref="pagination"
class="bottom-pagination"
layout="total, prev, pager, next"
:current-page.sync="currentPage"
:page-size="pageSize"
:total="totalCount"
@size-change="sizeChange"
@current-change="handleCurrentChange"></el-pagination>
Copy the code
- When possible, import files use absolute paths, while components on the current page use relative paths, so that when moving folders, dependencies are not found
Other Style Guides
- Google JavaScript Style Guide
- jQuery Core Style Guidelines
- Principles of Writing Consistent, Idiomatic JavaScript
reference
- Write maintainable JavaScript
- yuche/javascript
- css-style-guide