Play with code | Share some practical Vue front-end code (2)

Table of contents

Edit

2. Code specifications

2.1 Vue

2.1.1 Code structure

2.1.2 data

2.1.3 prop

2.1.4 computed

2.1.5 Set key values ​​for v-for

2.1.6 v-if and v-for are mutually exclusive

2.1.7 Elements with multiple attributes

2.1.8 Simple expressions in templates

2.1.9 Quoted attribute values

2.1.10 Instruction abbreviation

2.2 HTML

2.2.1 File template

2.2.2 Element and label closure

2.2.3 Code nesting

2.3 CSS

2.3.1 Style files

2.3.2 Code formatting

2.3.3 Code case

2.3.4 Code readability

2.3.5 Quotation marks for attribute values

2.3.6 Suggestions for writing attributes

3.3.7 CSS3 browser private prefix

2.4 JavaScript

2.4.1 Single-line code blocks

2.4.2 Curly brace style

2.4.3 Spaces in code


2. Code specifications

2.1 Vue

2.1.1 Code structure

<template>
  <div id="my-component">
    <DemoComponent />
  </div>
</template>

<script>
import DemoComponent from '../components/DemoComponent'

export default {
  name: 'MyComponent',
  components: {
    DemoComponent
  },
  mixins: [],
  props: {},
  data () {
    return {}
  },
  computed: {},
  watch: {}
  created () {},
  mounted () {},
  destroyed () {},
  methods: {},
}
</script>

<style lang="scss" scoped>
#my-component {
}
</style>

2.1.2 data

The component  data must be a function.

// In a .vue file
export default {
  data () {
    return {
      foo: 'bar'
    }
  }
}

2.1.3 prop

Prop definitions should be as detailed as possible.

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

2.1.4 computed

Complex computed properties should be split into as many simpler properties as possible.  Small, focused computational properties reduce assumptions about the use of information, so less refactoring is required when requirements change.

// bad
computed: { 
  price: function () { 
    var basePrice = this.manufactureCost / (1 - this.profitMargin) 
    return ( 
      basePrice - 
      basePrice * (this.discountPercent || 0) 
    ) 
  } 
}

// good
computed: {
  basePrice: function () {
    return this.manufactureCost / (1 - this.profitMargin)
  },
  discount: function () {
    return this.basePrice * (this.discountPercent || 0)
  },
  finalPrice: function () {
    return this.basePrice - this.discount
  }
}

2.1.5 To  v-for set the key value

Collocations must be used on components  key in v-for order to maintain the state of the internal component and its subtrees. Even maintain predictable behavior on elements, such as object constancy in animations .

<ul>
  <li
    v-for="todo in todos"
    :key="todo.id">
      {
   
   { todo.text }}
  </li>
</ul>
 
 

2.1.6  v-if and  v-for mutual exclusion

Never  use both v-if and  v-for on the same element.

<!-- bad:控制台报错 -->
<ul>
  <li
    v-for="user in users"
    v-if="shouldShowUsers"
    :key="user.id">
      {
   
   { user.name }}
  </li>
</ul>

Generally we tend to do this in two common situations:

  • To filter items in a list (for example  v-for="user in users" v-if="user.isActive"). In this case,  users replace with a computed property (for example  activeUsers) that returns the filtered list.
computed: {
  activeUsers: function () {
    return this.users.filter((user) => {
      return user.isActive
    })
  }
}
<ul>
  <li
    v-for="user in activeUsers"
    :key="user.id">
      {
   
   { user.name }}
  </li>
</ul>
  • To avoid rendering a list that should be hidden (for example  v-for="user in users" v-if="shouldShowUsers"). In this case,  v-if move it to the container element (for example  ulol).
    <!-- 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>

2.1.7 Elements with multiple attributes

Elements with multiple attributes should be written on multiple lines, one line for each attribute.

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

<!-- good -->
<img
  src="https://vuejs.org/images/logo.png"
  alt="Vue Logo">

<MyComponent
  foo="a"
  bar="b"
  baz="c"/>

2.1.8 Simple expressions in templates

Component templates should only contain simple expressions, and complex expressions should be refactored into computed properties or methods.

Complex expressions make your templates less declarative. We should try to describe what should appear , not how to calculate that value. And computed properties and methods make code reusable.

// bad
{
   
   {
  fullName.split(' ').map((word) => {
    return word[0].toUpperCase() + word.slice(1)
  }).join(' ')
}}

Better approach:

<!-- 在模板中 -->
{
   
   { normalizedFullName }}

// 复杂表达式已经移入一个计算属性
computed: {
  normalizedFullName: function () {
    return this.fullName.split(' ').map(function (word) {
      return word[0].toUpperCase() + word.slice(1)
    }).join(' ')
  }
}

2.1.9 Quoted attribute values

Non-empty HTML attribute values ​​should always be enclosed in double quotes.

<!-- bad -->
<input type=text>
<AppSidebar :style={width:sidebarWidth+'px'}>
<!-- good -->
<input type="text">
<AppSidebar :style="{ width: sidebarWidth + 'px' }">

2.1.10 Instruction abbreviation

  • : expressed  by v-bind:
  • @ expressed  by v-on:
  • # expressed  by v-slot:
<input
  :value="newTodoText"
  :placeholder="newTodoInstructions">

<input
  @input="onInput"
  @focus="onFocus">

<template #header>
  <h1>Here might be a page title</h1>
</template>

<template #footer>
  <p>Here's some contact info</p>
</template>

2.2 HTML

2.2.1 File template

HTML5 file template:

<!DOCTYPE html>
  <html lang="zh-CN">
  <head>
    <meta charset="UTF-8">
    <title>HTML5标准模版</title>
  </head>
  <body>
  </body>
</html>

Mobile version:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
    <meta name="format-detection" content="telephone=no">
    <title>移动端HTML模版</title>

    <!-- S DNS预解析 -->
    <link rel="dns-prefetch" href="">
    <!-- E DNS预解析 -->

    <!-- S 线上样式页面片,开发请直接取消注释引用 -->
    <!-- #include virtual="" -->
    <!-- E 线上样式页面片 -->

    <!-- S 本地调试,根据开发模式选择调试方式,请开发删除 -->
    <link rel="stylesheet" href="css/index.css">
    <!-- /本地调试方式 -->

    <link rel="stylesheet" href="http://srcPath/index.css">
    <!-- /开发机调试方式 -->
    <!-- E 本地调试 -->

</head>
<body>
</body>
</html>
 
 

PC version:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="keywords" content="your keywords">
    <meta name="description" content="your description">
    <meta name="author" content="author,email address">
    <meta name="robots" content="index,follow">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta name="renderer" content="ie-stand">
    <title>PC端HTML模版</title>

    <!-- S DNS预解析 -->
    <link rel="dns-prefetch" href="">
    <!-- E DNS预解析 -->

    <!-- S 线上样式页面片,开发请直接取消注释引用 -->
    <!-- #include virtual="" -->
    <!-- E 线上样式页面片 -->

    <!-- S 本地调试,根据开发模式选择调试方式,请开发删除 -->
    <link rel="stylesheet" href="css/index.css">
    <!-- /本地调试方式 -->

    <link rel="stylesheet" href="http://srcPath/index.css">
    <!-- /开发机调试方式 -->
    <!-- E 本地调试 -->
</head>
<body>
</body>
</html>
 
 

2.2.2 Element and label closure

There are five types of HTML elements:

  • 空元素:area、base、br、col、command、embed、hr、img、input、keygen、link、meta、param、source、track、wbr
  • Original text elements: script, style
  • RCDATA elements: textarea, title
  • Foreign elements: elements from the MathML namespace and SVG namespace
  • Regular elements: Other elements allowed by HTML are called regular elements

In order to allow browsers to better parse the code and make the code more readable, the following conventions are adopted:

  • All elements with start tags and end tags must be written with start and end tags, and some elements that allow the omission of start tags or bundle tags must also be written.
  • Empty element tags do not include the "/" character.
    <!-- good -->
    <div>
        <h1>我是h1标题</h1>
        <p>我是一段文字,我有始有终,浏览器能正确解析</p>
    </div>
    	
    <br data-tomark-pass>
    
    <!-- bad -->
    <div>
        <h1>我是h1标题</h1>
        <p>我是一段文字,我有始无终,浏览器亦能正确解析
    </div>
    
    <br/>

2.2.3 Code nesting

Element nesting specifications, each block element is on its own line, and inline elements are optional.

<!-- good -->
<div>
    <h1></h1>
    <p></p>
</div>	
<p><span></span><span></span></p>

<!-- bad -->
<div>
    <h1></h1><p></p>
</div>	
<p> 
    <span></span>
    <span></span>
</p>

Paragraph elements and title elements can only nest inline elements.

<!-- good -->
<h1><span></span></h1>
<p><span></span><span></span></p>

<!-- bad -->
<h1><div></div></h1>
<p><div></div><div></div></p>

2.3 CSS

2.3.1 Style files

The style file must be written with  @charset rules, and it must be written starting from the first character on the first line of the style file, and the encoding name is used  “UTF-8”.

  • recommend:
@charset "UTF-8";
.jdc {}
  • Not recommended:
/* @charset规则不在文件首行首个字符开始 */
@charset "UTF-8";
.jdc {}

/* @charset规则没有用小写 */
@CHARSET "UTF-8";
.jdc {}

/* 无@charset规则 */
.jdc {}

2.3.2 Code formatting

There are generally two styles of writing: one is compact format (Compact) and the other is expanded format (Expanded).

  • Recommended: Expanded format
.jdc {
  display: block;
  width: 50px;
}
  • Not recommended: Compact format (Compact)
.jdc { display: block; width: 50px;}

2.3.3 Code case

Style selectors, attribute names, and attribute value keywords are all written in lowercase letters, and uppercase and lowercase letters are allowed in attribute strings.

  • recommend:
.jdc {
  display: block;
}
  • Not recommended:
.JDC {
  DISPLAY: BLOCK;
}

2.3.4 Code readability

  1. There is a space between the opening bracket and the class name, and a space between the colon and the attribute value.
  • recommend:
.jdc {
  width: 100%;
}
  • Not recommended:
.jdc{
  width:100%;
}
  1. Comma separated values, followed by a space.
  • recommend:
.jdc {
  box-shadow: 1px 1px 1px #333, 2px 2px 2px #ccc;
}
  • Not recommended:
.jdc {
  box-shadow: 1px 1px 1px #333,2px 2px 2px #ccc;
}
  1. Opens a new line for a single CSS selector or new declaration.
  • recommend:
.jdc, .jdc_logo, .jdc_hd {
  color: #ff0;
}

.nav{
  color: #fff;
}
  • Not recommended:
.jdc, .jdc_logo, .jdc_hd {
  color: #ff0;
}.nav{
  color: #fff;
}
  1. There are no spaces in the color value  rgb() rgba() hsl() hsla() rect() , and the value should not contain unnecessary 0s.
  • recommend:
.jdc {
  color: rgba(255,255,255,.5);
}
  • Not recommended:
.jdc {
  color: rgba( 255, 255, 255, 0.5 );
}
  1. If the hexadecimal value of the attribute value can be abbreviated, use abbreviations as much as possible.
  • recommend:
.jdc {
  color: #fff;
}
  • Not recommended:
.jdc {
  color: #ffffff;
}
  1. Do not  0 specify units.
  • recommend:
.jdc {
  margin: 0 10px;
}
  • Not recommended:
.jdc {
  margin: 0px 10px;
}

2.3.5 Quotation marks for attribute values

When quotation marks are required for CSS property values, single quotation marks should be used.

  • recommend:
.jdc {
  font-family: 'Hiragino Sans GB';
}
  • Not recommended:
.jdc {
  font-family: "Hiragino Sans GB";
}

2.3.6 Suggestions for writing attributes

It is recommended to follow the following sequence:

  1. Layout positioning properties: display / position / float / clear / visibility / overflow
  2. Self attributes: width / height / margin / padding / border / background
  3. Text properties: color/font/text-decoration/text-align/vertical-align/white-space/break-word
  4. Other properties (CSS3): content/cursor/border-radius/box-shadow/text-shadow/background: linear-gradient…
.jdc {
  display: block;
  position: relative;
  float: left;
  width: 100px;
  height: 100px;
  margin: 0 10px;
  padding: 20px 0;
  font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
  color: #333;
  background: rgba(0,0,0,.5);
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -o-border-radius: 10px;
  -ms-border-radius: 10px;
  border-radius: 10px;
}

3.3.7 CSS3 browser private prefix

CSS3 browser-specific prefixes come first and standard prefixes follow.

.jdc {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -o-border-radius: 10px;
  -ms-border-radius: 10px;
  border-radius: 10px;
}

2.4 JavaScript

2.4.1 Single-line code blocks

Use spaces within single-line code blocks.

  • Not recommended:
function foo () {return true}
if (foo) {bar = 0}
  • recommend:
function foo () { return true }
if (foo) { bar = 0 }

2.4.2 Curly brace style

In the programming process, brace style is closely related to indentation style, and there are many ways to describe the position of braces relative to the code block. In JavaScript, there are three main styles, as follows:

  • 【Recommended】One True Brace Style
if (foo) {
  bar()
} else {
  baz()
}
  • Stroustrup
if (foo) {
  bar()
}
else {
  baz()
}
  • Allman
if (foo)
{
  bar()
}
else
{
  baz()
}

2.4.3 Spaces in code

  1. Spaces before and after commas can improve the readability of the code. The team has agreed to use spaces after commas and no spaces before commas.
  • recommend:
var foo = 1, bar = 2
  • Not recommended:
var foo = 1,bar = 2

var foo = 1 , bar = 2

var foo = 1 ,bar = 2
  1. There cannot be a space between the key and value of an object literal, and a space is required between the colon and the value of the object literal.
  • recommend:
var obj = { 'foo': 'haha' }
  • Not recommended:
var obj = { 'foo' : 'haha' }
  1. Add spaces before code blocks.
  • recommend:
if (a) {
  b()
}

function a () {}
  • Not recommended:
if (a){
  b()
}

function a (){}
  1. There must be a space before the function declaration parentheses.
  • recommend:
function func (x) {
  // ...
}
  • Not recommended
function func(x) {
  // ...
}
  1. When calling a function, spaces are prohibited.
  • recommend:
fn()
  • Not recommended:
fn ()

fn
()
  1. You need to add spaces before and after the operator.
  • recommend:
var sum = 1 + 2
  • Not recommended:
var sum = 1+2

Guess you like

Origin blog.csdn.net/qq_22903531/article/details/132622223