前端規范

Vue 開發規范目錄及說明

本文檔為前端 vue 開發規范

  • 規范目的
  • 命名規范
  • 結構化規范
  • 注釋規范
  • 編碼規范
  • CSS 規范

規范目的

為提高團隊協作效率

便于后臺人員添加功能及前端后期優化維護

輸出高質量的文檔

命名規范

為了讓大家書寫可維護的代碼,而不是一次性的代碼

讓團隊當中其他人看你的代碼能一目了然

甚至一段時間時候后你再看你某個時候寫的代碼也能看

普通變量命名規范

  • 命名方法 :駝峰命名法

  • 命名規范 :

    1. 命名必須是跟需求的內容相關的詞,比如說我想申明一個變量,用來表示我的學校,那么我們可以這樣定義const mySchool = "我的學校";

    2. 命名是復數的時候需要加s,比如說我想申明一個數組,表示很多人的名字,那么我們可以這樣定義const names = new Array();

常量

  • 命名方法 : 全部大寫
  • 命名規范 : 使用大寫字母和下劃線來組合命名,下劃線用以分割單詞。
const MAX_COUNT = 10
const URL = 'https://www.baidu.com/'
復制代碼

組件命名規范

官方文檔推薦及使用遵循規則:

PascalCase (單詞首字母大寫命名)是最通用的聲明約定

kebab-case (短橫線分隔命名) 是最通用的使用約定

  • 組件名應該始終是多個單詞的,根組件 App 除外

  • 有意義的名詞、簡短、具有可讀性

  • 命名遵循 PascalCase 約定

    • 公用組件以 Abcd (公司名縮寫簡稱) 開頭,如(AbcdDatePicker,AbcdTable

    • 頁面內部組件以組件模塊名簡寫為開頭,Item 為結尾,如(StaffBenchToChargeItem,StaffBenchAppNotArrItem

  • 使用遵循 kebab-case 約定

    • 在頁面中使用組件需要前后閉合,并以短線分隔,如(<abcd-date-picker></abcd-date-picker>,<abcd-table></abcd-table>
  • 導入及注冊組件時,遵循 PascalCase 約定

  • 同時還需要注意:必須符合自定義元素規范: 切勿使用保留字。

method 方法命名命名規范

  • 駝峰式命名,統一使用動詞或者動詞+名詞形式
  //bad
  go、nextPage、show、open、login

    // good
  jumpPage、openCarInfoDialog

復制代碼
  • 請求數據方法,以 data 結尾
  //bad
  takeData、confirmData、getList、postForm

  // good
  getListData、postFormData
復制代碼
  • init、refresh 單詞除外

  • 盡量使用常用單詞開頭(set、get、go、can、has、is)

附: 函數方法常用的動詞:

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 聚集
復制代碼

views 下的文件命名

  • 只有一個文件的情況下不會出現文件夾,而是直接放在 views 目錄下面,如 index.vue

  • 盡量是名詞,且使用駝峰命名法

  • 開頭的單詞就是所屬模塊名字(workbenchIndex、workbenchList、workbenchEdit)

  • 名字至少兩個單詞(good: workbenchIndex)(bad:workbench)

props 命名

在聲明 prop 的時候,其命名應該始終使用 camelCase,而在模板中應該始終使用 kebab-case

<!-- 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>
復制代碼

例外情況

  1. 作用域不大臨時變量可以簡寫,比如:str,num,bol,obj,fun,arr。

  2. 循環變量可以簡寫,比如:i,j,k 等。

結構化規范

目錄文件夾及子文件規范

  • 以下統一管理處均對應相應模塊
  • 以下全局文件文件均以 index.js 導出,并在 main.js 中導入
  • 以下臨時文件,在使用后,接口已經有了,發版后清除
src                               源碼目錄
|-- api                              接口,統一管理
|-- assets                           靜態資源,統一管理
|-- components                       公用組件,全局文件
|-- filters                          過濾器,全局工具
|-- icons                            圖標,全局資源
|-- datas                            模擬數據,臨時存放
|-- lib                              外部引用的插件存放及修改文件
|-- mock                             模擬接口,臨時存放
|-- router                           路由,統一管理
|-- store                            vuex, 統一管理
|-- views                         視圖目錄
|   |-- staffWorkbench               視圖模塊名
|   |-- |-- staffWorkbench.vue       模塊入口頁面
|   |-- |-- indexComponents          模塊頁面級組件文件夾
|   |-- |-- components               模塊通用組件文件夾
復制代碼

vue 文件基本結構

  <template>
    <div>
      <!--必須在div中編寫頁面-->
    </div>
  </template>
  <script>
    export default {
      components : {
      },
      data () {
        return {
        }
      },
      mounted() {
      },
      methods: {
      }
   }
  </script>
  <!--聲明語言,并且添加scoped-->
  <style lang="scss" scoped>
  </style>
復制代碼

多個特性的元素規范

多個特性的元素應該分多行撰寫,每個特性一行。(增強更易讀)

<!-- 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>
復制代碼

元素特性的順序

原生屬性放前面,指令放后面

如下所示:

  - 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
復制代碼

組件選項順序

如下所示:

  - components
  - props
  - data
  - computed
  - created
  - mounted
  - metods
  - filter
  - watch
復制代碼

注釋規范

代碼注釋在一個項目的后期維護中顯的尤為重要,所以我們要為每一個被復用的組件編寫組件使用說明,為組件中每一個方法編寫方法說明

務必添加注釋列表

  1. 公共組件使用說明

  2. 各組件中重要函數或者類說明

  3. 復雜的業務邏輯處理說明

  4. 特殊情況的代碼處理說明,對于代碼中特殊用途的變量、存在臨界值、函數中使用的 hack、使用了某種算法或思路等需要進行注釋描述

  5. 多重 if 判斷語句

  6. 注釋塊必須以/**(至少兩個星號)開頭**/

  7. 單行注釋使用//

單行注釋

注釋單獨一行,不要在代碼后的同一行內加注釋。例如:

  bad

  var name =”abc”; // 姓名    

  good

  // 姓名
  var name = “abc”;         
復制代碼

多行注釋

組件使用說明,和調用說明
      /**
      * 組件名稱
      * @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>
      **/
復制代碼

編碼規范

優秀的項目源碼,即使是多人開發,看代碼也如出一人之手。統一的編碼規范,可使代碼更易于閱讀,易于理解,易于維護。盡量按照 ESLint 格式要求編寫代碼

源碼風格

使用 ES6 風格編碼

  1. 定義變量使用 let ,定義常量使用 const

  2. 靜態字符串一律使用單引號或反引號,動態字符串使用反引號

  // 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. 解構賦值
  • 數組成員對變量賦值時,優先使用解構賦值
  // 數組解構賦值
  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 }) {}
復制代碼
  1. 拷貝數組

    使用擴展運算符(...)拷貝數組。

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

  // bad
  const itemsCopy = items

  // good
  const itemsCopy = [...items]
復制代碼
  1. 箭頭函數

    需要使用函數表達式的場合,盡量用箭頭函數代替。因為這樣更簡潔,而且綁定了 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. 模塊
  • 如果模塊只有一個輸出值,就使用 export default,如果模塊有多個輸出值,就不使用 export default,export default 與普通的 export 不要同時使用
  // bad
  import * as myObject from './importModule'

  // good
  import myObject from './importModule'
復制代碼
  • 如果模塊默認輸出一個函數,函數名的首字母應該小寫。
  function makeStyleGuide() {
  }

  export default makeStyleGuide;
復制代碼
  • 如果模塊默認輸出一個對象,對象名的首字母應該大寫。
  const StyleGuide = {
    es6: {
    }
  };

  export default StyleGuide;
復制代碼

指令規范

  1. 指令有縮寫一律采用縮寫形式
  // bad
  v-bind:class="{'show-left':true}"
  v-on:click="getListData"

  // good
  :class="{'show-left':true}"
  @click="getListData"
復制代碼
  1. v-for 循環必須加上 key 屬性,在整個 for 循環中 key 需要唯一
  <!-- 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. 避免 v-if 和 v-for 同時用在一個元素上(性能問題)

    以下為兩種解決方案:

  • 將數據替換為一個計算屬性,讓其返回過濾后的列表
  <!-- 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>
復制代碼
  • 將 v-if 移動至容器元素上 (比如 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 規范

Props 定義應該盡量詳細

// bad 這樣做只有開發原型系統時可以接受
props: ['status']

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

其他

  1. 避免 this.$parent

  2. 調試信息 console.log() debugger 使用完及時刪除

  3. 除了三目運算,if,else 等禁止簡寫

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

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

  // good
  if (true) {
      alert(name);
  }
  console.log(name);
復制代碼

CSS 規范

通用規范

  1. 統一使用"-"連字符

  2. 省略值為 0 時的單位

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

 // good
  padding-bottom: 0;
  margin: 0;
復制代碼
  1. 如果 CSS 可以做到,就不要使用 JS

  2. 建議并適當縮寫值,提高可讀性,特殊情況除外

    “建議并適當”是因為縮寫總是會包含一系列的值,而有時候我們并不希望設置某一值,反而造成了麻煩,那么這時候你可以不縮寫,而是分開寫。

    當然,在一切可以縮寫的情況下,請務必縮寫,它最大的好處就是節省了字節,便于維護,并使閱讀更加一目了然。

  // 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. 聲明應該按照下表的順序

左到右,從上到下

顯示屬性 自身屬性 文本屬性和其他修飾
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. 元素選擇器應該避免在 scoped 中出現

    官方文檔說明:在 scoped 樣式中,類選擇器比元素選擇器更好,因為大量使用元素選擇器是很慢的。

  2. 分類的命名方法

    使用單個字母加上"-"為前綴

    布局(grid)(.g-);

    模塊(module)(.m-);

    元件(unit)(.u-);

    功能(function)(.f-);

    皮膚(skin)(.s-);

    狀態(.z-)。

  3. 統一語義理解和命名

布局(.g-)

語義 命名 簡寫
文檔 doc doc
頭部 head hd
主體 body bd
尾部 foot ft
主欄 main mn
主欄子容器 mainc mnc
側欄 side sd
側欄子容器 sidec sdc
盒容器 wrap/box wrap/box

模塊(.m-)、元件(.u-)

語義 命名 簡寫
導航 nav nav
子導航 subnav snav
面包屑 crumb crm
菜單 menu menu
選項卡 tab tab
標題區 head/title hd/tt
內容區 body/content bd/ct
列表 list lst
表格 table tb
表單 form fm
熱點 hot hot
排行 top top
登錄 login log
標志 logo logo
廣告 advertise ad
搜索 search sch
幻燈 slide sld
提示 tips tips
幫助 help help
新聞 news news
下載 download dld
注冊 regist reg
投票 vote vote
版權 copyright cprt
結果 result rst
標題 title tt
按鈕 button btn
輸入 input ipt

功能(.f-)

語義 命名 簡寫
浮動清除 clearboth cb
向左浮動 floatleft fl
向右浮動 floatright fr
內聯塊級 inlineblock ib
文本居中 textaligncenter tac
文本居右 textalignright tar
文本居左 textalignleft tal
垂直居中 verticalalignmiddle vam
溢出隱藏 overflowhidden oh
完全消失 displaynone dn
字體大小 fontsize fs
字體粗細 fontweight fw

皮膚(.s-)

語義 命名 簡寫
字體顏色 fontcolor fc
背景 background bg
背景顏色 backgroundcolor bgc
背景圖片 backgroundimage bgi
背景定位 backgroundposition bgp
邊框顏色 bordercolor bdc

狀態(.z-)

語義 命名 簡寫
選中 selected sel
當前 current crt
顯示 show show
隱藏 hide hide
打開 open open
關閉 close close
出錯 error err
不可用 disabled dis

sass 規范

  1. 當使用 Sass 的嵌套功能的時候,重要的是有一個明確的嵌套順序,以下內容是一個 SCSS 塊應具有的順序。

    1. 當前選擇器的樣式屬性
    2. 父級選擇器的偽類選擇器 (:first-letter, :hover, :active etc)
    3. 偽類元素 (:before and :after)
    4. 父級選擇器的聲明樣式 (.selected, .active, .enlarged etc.)
    5. 用 Sass 的上下文媒體查詢
    6. 子選擇器作為最后的部分
  .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;
      }
    }
  }
復制代碼

特殊規范

  • 對用頁面級組件樣式,應該是有作用域的
  • 對于公用組件或者全局組件庫,我們應該更傾向于選用基于 class 的 BEM 策略
  <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>
復制代碼

參考

風格指南

更好的css方案

前端js規范文檔
https://juejin.cn/post/6844903652096770055#heading-29

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。