The most complete Vue development specification in history

The most complete Vue development specification in history

Vue development specification catalog and description

This document is the front-end vue development specification

  • Normative purpose
  • Naming conventions
  • Structured specification
  • Annotation specification
  • Coding Standards
  • CSS specification

Normative purpose

To improve the efficiency of teamwork

It is convenient for back-end personnel to add functions and optimize the maintenance of the front-end

Output high-quality documents

Naming conventions

In order for everyone to write maintainable code, not one-time code

Let others on the team see your code at a glance

Even after a while, you can read the code you wrote at a certain time.

Common variable naming convention

  • Nomenclature: camel case nomenclature

  • Naming conventions:

    1. The naming must be a word related to the content of the requirement. For example, if I want to declare a variable to represent my school, then we can define it like this const mySchool = " ";

    2. When the naming is plural, s needs to be added . For example, I want to declare an array to represent the names of many people, then we can define it like this const names = new Array();

constant

  • Naming method: all uppercase
  • Naming convention: Use capital letters and underscores to combine names, and underscores are used to separate words.
const MAX_COUNT = 10
const URL = 'https://www.baidu.com/'
 

Component naming convention

The official document recommendation and usage follow the rules:

PascalCase (name with the first letter of a word) is the most common declaration convention

Kebab-case (name separated by dashes) is the most common usage convention

  • The component name should always be multiple words, except for the root component App

  • Meaningful nouns, short and readable

  • The naming follows the PascalCase convention

    • Common components start with Abcd (abbreviation of company name), such as ( AbcdDatePicker,AbcdTable)

    • The internal components of the page start with the abbreviated name of the component module and end with Item, such as ( StaffBenchToChargeItem StaffBenchAppNotArrItem)

  • Use follow the kebab-case convention

    • The components used in the page need to be closed before and after, and separated by short lines, such as ( <abcd-date-picker></abcd-date-picker> <abcd-table></abcd-table>)
  • When importing and registering components, follow the PascalCase convention

  • At the same time, you need to pay attention: must comply with the custom element specification: do not use reserved words.

method method naming convention

  • Camel case naming, uniform use of verb or verb + noun form
  //bad
  go nextPage show open login

    //good
  jumpPage openCarInfoDialog

 
  • Request data method, ending with data
  //bad
  takeData confirmData getList postForm

  //good
  getListData postFormData
 
  • Except init and refresh words

  • Try to start with common words (set, get, go, can, has, is)

Attachment: verbs commonly used in function methods:

get /set  ,
add /remove  
create /destory  
start /stop  
open /close  ,
read /write  
load /save  ,
create /destroy  
begin /end  ,
backup /restore  
import /export  ,
split /merge  
inject /extract  ,
attach /detach  
bind /separate  ,
view /browse  
edit /modify  ,
select /mark  
copy /paste  ,
undo /redo  
insert /delete  ,
add /append  
clean /clear  ,
index /sort  
find /search  ,
increase /decrease  
play /pause  ,
launch /run  
compile /execute  ,
debug /trace  
observe /listen  ,
build /publish  
input /output  ,
encode /decode  
encrypt /decrypt  ,
compress /decompress  
pack /unpack  ,
parse /emit  
connect /disconnect  ,
send /receive  
download /upload  ,
refresh /synchronize  
update /revert  ,
lock /unlock  
check out /check in  ,
submit /commit  
push /pull  ,
expand /collapse  
begin /end  ,
start /finish  
enter /exit  ,
abort /quit  
obsolete /depreciate  ,
collect /aggregate  
 

File naming under views

  • There is no folder when there is only one file, but it is placed directly under the views directory, such as index.vue

  • Try to be nouns and use camel case nomenclature

  • The first word is the name of the module (workbenchIndex, workbenchList, workbenchEdit)

  • At least two words in the name (good: workbenchIndex) (bad: workbench)

props naming

When declaring a prop, its naming should always use camelCase, and kebab-case should always be used in the template

<!-- bad -->
<script>
props: {
  'greeting-text': String
}
</script>

<welcome-message greetingText="hi"></welcome-message>

<!-- good -->
<script>
props: {
  greetingText: String
}
</script>

<welcome-message greeting-text="hi"></welcome-message>
 

exception

  1. Temporary variables with small scope can be abbreviated, such as: str, num, bol, obj, fun, arr.

  2. Loop variables can be abbreviated, such as: i, j, k, etc.

Structured specification

Directory folder and sub-file specification

  • The following unified management offices correspond to the corresponding modules
  • The following global files are exported as index.js and imported in main.js
  • The following temporary files, after use, the interface is already available, and will be cleared after the release
src                                
|-- api                               
|-- assets                            
|-- components                        
|-- filters                           
|-- icons                             
|-- datas                             
|-- lib                               
|-- mock                              
|-- router                            
|-- store                            vuex,  
|-- views                          
|   |-- staffWorkbench                
|   |-- |-- staffWorkbench.vue        
|   |-- |-- indexComponents           
|   |-- |-- components                
 

Basic structure of vue file

  <template>
    <div>
      <!-- div -->
    </div>
  </template>
  <script>
    export default {
      components : {
      },
      data () {
        return {
        }
      },
      mounted() {
      } 
      methods: {
      }
   }
  </script>
  <!-- scoped-->
  <style lang="scss" scoped>
  </style>
 

Multiple feature element specifications

Elements with multiple characteristics should be written in multiple lines, one line for each characteristic. (Enhanced to make it easier to read)

<!-- bad -->
<img src="https://vuejs.org/images/logo.png" alt="Vue Logo">
<my-component foo="a" bar="b" baz="c"></my-component>

<!-- good -->
<img
  src="https://vuejs.org/images/logo.png"
  alt="Vue Logo"
>
<my-component
  foo="a"
  bar="b"
  baz="c"
>
</my-component>
 

Order of element characteristics

Native attributes are placed in front, instructions are placed at the back

As follows:

  - 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-text
 

Order of component options

As follows:

  - components
  - props
  - data
  - computed
  - created
  - mounted
  - metods
  - filter
  - watch
 

Annotation specification

Code comments are particularly important in the post-maintenance of a project, so we have to write component instructions for each reused component, and write method instructions for each method in the component

Be sure to add a note list

  1. Instructions for use of public components

  2. Description of important functions or classes in each component

  3. Complicated business logic processing instructions

  4. Code handling instructions for special situations, comments and descriptions are required for special-purpose variables in the code, critical values, hacks used in functions, and certain algorithms or ideas used in the code

  5. Multiple if statement

  6. The comment block must start with/** **/

  7. Single-line comment use//

Single line comment

Comment on a single line, do not add comments on the same line after the code. E.g:

  bad

  var name = abc ;//     

  good

 // 
  var name =  abc ;         
 

Multi-line comments

 
     /**
      *  
      * @module  
      * @desc  
      * @author  
      * @date 2017 12 05 17:22:43
      * @param {Object} [title]    -  
      * @param {String} [columns] -  
      * @example  
      *  <hbTable :title="title" :columns="columns" :tableData="tableData"></hbTable>
      **/
 

Coding Standards

Excellent project source code, even if it is developed by multiple people, looking at the code is like one person. Uniform coding standards can make the code easier to read, understand, and maintain. Try to write code in accordance with ESLint format requirements

Source code style

Use ES6 style coding

  1. Use let to define variables and const to define constants

  2. Use single quotes or backquotes for static strings, and use backquotes for dynamic strings

 //bad
  const a = 'foobar'
  const b = 'foo' + a + 'bar'

 //acceptable
  const c = `foobar`

 //good
  const a = 'foobar'
  const b = `foo${a}bar`
  const c = 'foobar'
 
  1. Destructuring assignment
  • When array members assign values to variables, destructuring assignment is preferred
 // 
  const arr = [1, 2, 3, 4]
 //bad
  const first = arr[0]
  const second = arr[1]

 //good
  const [first, second] = arr
 
  • If the parameter of the function is a member of the object, use destructuring assignment first
 // 
 //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 }) {}
 
  1. Copy array

    Use the spread operator (...) to copy the array.

  const items = [1, 2, 3, 4, 5]

 //bad
  const itemsCopy = items

 //good
  const itemsCopy = [...items]
 
  1. Arrow function

    When you need to use function expressions, try to use arrow functions instead. Because it is more concise, and binds this

 //bad
  const self = this;
  const boundMethod = function(...params) {
    return method.apply(self, params);
  }

 //acceptable
  const boundMethod = method.bind(this);

 //best
  const boundMethod = (...params) => method.apply(this, params);
 
  1. Module
  • If the module has only one output value, use export default. If the module has multiple output values, do not use export default. Do not use export default and ordinary export at the same time.
 //bad
  import * as myObject from './importModule'

 //good
  import myObject from './importModule'
 
  • If the module outputs a function by default, the first letter of the function name should be lowercase.
  function makeStyleGuide() {
  }

  export default makeStyleGuide;
 
  • If the module outputs an object by default, the first letter of the object name should be capitalized.
  const StyleGuide = {
    es6: {
    }
  };

  export default StyleGuide;
 

Directive specifications

  1. Commands with abbreviations are always in abbreviated form
  //bad
  v-bind:class="{'show-left' true}"
  v-on:click="getListData"

  //good
  :class="{'show-left' true}"
  @click="getListData"
 
  1. The key attribute must be added to the v-for loop, and the key must be unique in the entire for loop
  <!-- good -->
  <ul>
    <li v-for="todo in todos" :key="todo.id">
      {{ todo.text }}
    </li>
  </ul>

  <!-- bad -->
  <ul>
    <li v-for="todo in todos">
      {{ todo.text }}
    </li>
  </ul>
 
  1. Avoid using v-if and v-for on the same element at the same time (performance issue)

    The following are two solutions:

  • Replace the data with a calculated attribute and return it to 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>
 
  • Move v-if to the container element (e.g. 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>
 

Props specification

Props definition should be as detailed as possible

//bad  
props: ['status']

//good
props: {
  status: {
    type: String,
    required: true,
    validator: function (value) {
      return [
        'syncing',
        'synced',
        'version-conflict',
        'error'
      ].indexOf(value) !== -1
    }
  }
}
 

other

  1. Avoid this.$parent

  2. Debug information console.log() debugger delete immediately after use

  3. Except for trinocular operations, if, else, etc. are not abbreviated

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

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

 //good
  if (true) {
      alrt(name);
  }
  console.log(name);
 

CSS specification

General specification

  1. Use "-" hyphens uniformly

  2. Omit the unit when the value is 0

//bad
  padding-bottom: 0px;
  margin: 0em;

//good
  padding-bottom: 0;
  margin: 0;
 
  1. If CSS can do it, don't use JS

  2. Suggest and appropriately abbreviate values to improve readability, except in special cases

    "Recommended and appropriate" is because the abbreviation always contains a series of values, and sometimes we don't want to set a certain value, but cause trouble, then you can not abbreviate, but write separately.

    Of course, in all cases that can be abbreviated, be sure to abbreviate. Its biggest advantage is that it saves bytes, is easy to maintain, and makes reading more clear.

 //bad
  .box{
    border-top-style: none;
    font-family: palatino, georgia, serif;
    font-size: 100%;
    line-height: 1.6;
    padding-bottom: 2em;
    padding-left: 1em;
    padding-right: 1em;
    padding-top: 0;
  }

 //good
  .box{
    border-top: 0;
    font: 100%/1.6 palatino, georgia, serif;
    padding: 0 1em 2em;
  }
 
  1. The declaration should be in the order of the following table

Left to right, top to bottom

Display attributes Own attributes Text attributes and other decorations
display width font
visibility height text-align
position margin text-decoration
float padding vertical-align
clear border white-space
list-style overflow color
top min-width background
 //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;
    font-size: 1.5rem;
    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;
    font-size: 1.5rem;
    text-transform: uppercase;
  }
 
  1. Element selectors should avoid appearing in scoped

    The official documentation states : In scoped style, class selectors are better than element selectors because it is very slow to use element selectors a lot.

  2. Classification naming method

    Use a single letter plus "-" as a prefix

    Layout (grid) (.g-);

    Module (.m-);

    Unit (.u-);

    Function (.f-);

    Skin (.s-);

    Status (.z-).

  3. Unified semantic understanding and naming

Layout (.g-)

Semantics name Shorthand
Documentation doc doc
head head hd
main body body bd
Tail foot ft
Main column main mn
Main column container mainc mnc
Sidebar side sd
Sidebar subcontainer sidec sdc
Box container wrap/box wrap/box

Module (.m-), component (.u-)

Semantics name Shorthand
navigation nav nav
Sub-navigation subnav snav
Bread crumbs crumb crm
menu menu menu
Tab tab tab
Title area head/title hd/tt
Content area body/content bd/ct
List list lst
form table tb
Form form fm
Hot spot hot hot
ranking top top
log in login log
Sign logo logo
advertising advertise ad
search for search sch
Slide slide sld
prompt tips tips
help help help
news news news
download download dld
registered regist reg
vote vote vote
copyright copyright cprt
result result rst
title title tt
Button button btn
enter input ipt

Function (.f-)

Semantics name Shorthand
Float clear clearboth cb
Float left floatleft fl
Float right floatright fr
Inline block level inlineblock ib
Text centered textaligncenter tac
Text right textalignright tar
Text left textalignleft tal
Vertically centered verticalalignmiddle vam
Overflow hiding overflowhidden oh
Completely disappear displaynone dn
font size fontsize fs
Font weight fontweight fw

Skin (.s-)

Semantics name Shorthand
font color fontcolor fc
background background bg
background color backgroundcolor bgc
Background picture backgroundimage bgi
Background positioning backgroundposition bgp
Border color bordercolor bdc

Status (.z-)

Semantics name Shorthand
Selected selected sel
current current crt
display show show
hide hide hide
turn on open open
shut down close close
Error error err
unavailable disabled dis

sass specification

  1. When using Sass's nesting function, it is important to have a clear nesting order. The following is the order that a SCSS block should have.

    1. The style attributes of the current selector
    2. Pseudo-class selector of the parent selector (:first-letter, :hover, :active etc)
    3. Pseudo element (:before and :after)
    4. The declaration style of the parent selector (.selected, .active, .enlarged etc.)
    5. Contextual media queries with Sass
    6. Sub-selector as the last part
  .product-teaser {
   //1. Style attributes
    display: inline-block;
    padding: 1rem;
    background-color: whitesmoke;
    color: grey;

   //2. Pseudo selectors with parent selector
    &:hover {
      color: black;
    }

   //3. Pseudo elements with parent selector
    &:before {
      content: "";
      display: block;
      border-top: 1px solid grey;
    }

    &:after {
      content: "";
      display: block;
      border-top: 1px solid grey;
    }

   //4. State classes with parent selector
    &.active {
      background-color: pink;
      color: red;

     //4.2. Pseuso selector in state class selector
      &:hover {
        color: darkred;
      }
    }

   //5. Contextual media queries
    @media screen and (max-width: 640px) {
      display: block;
      font-size: 2em;
    }

   //6. Sub selectors
    > .content > .title {
      font-size: 1.2em;

     //6.5. Contextual media queries in sub selector
      @media screen and (max-width: 640px) {
        letter-spacing: 0.2em;
        text-transform: uppercase;
      }
    }
  }
 

Special specification

  • For page-level component styles, there should be scope
  • For public components or global component libraries, we should be more inclined to choose a class-based BEM strategy
  <style lang='scss'></style> //bad

  <!--   scoped   -->
  <style lang='scss' scoped></style> //good

  <!--   BEM   -->
  <style>//good
  .c-Button {
    border: none;
    border-radius: 2px;
  }

  .c-Button--close {
    background-color: red;
  }
  </style>
 

reference

Style guide

Better css solution

Front-end js specification document