本文檔爲前端 vue 開發規範javascript
爲提升團隊協做效率css
便於後臺人員添加功能及前端後期優化維護html
輸出高質量的文檔前端
爲了讓你們書寫可維護的代碼,而不是一次性的代碼vue
讓團隊當中其餘人看你的代碼能一目瞭然java
甚至一段時間時候後你再看你某個時候寫的代碼也能看es6
命名方法 :駝峯命名法算法
命名規範 :vuex
命名必須是跟需求的內容相關的詞,好比說我想申明一個變量,用來表示個人學校,那麼咱們能夠這樣定義const mySchool = "個人學校"
;api
命名是複數的時候須要加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 約定
同時還須要注意:必須符合自定義元素規範: 切勿使用保留字。
//bad
go、nextPage、show、open、login
// good
jumpPage、openCarInfoDialog
複製代碼
//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 目錄下面,如 index.vue
儘可能是名詞,且使用駝峯命名法
開頭的單詞就是所屬模塊名字(workbenchIndex、workbenchList、workbenchEdit)
名字至少兩個單詞(good: workbenchIndex)(bad:workbench)
在聲明 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>
複製代碼
做用域不大臨時變量能夠簡寫,好比:str,num,bol,obj,fun,arr。
循環變量能夠簡寫,好比:i,j,k 等。
src 源碼目錄
|-- api 接口,統一管理
|-- assets 靜態資源,統一管理
|-- components 公用組件,全局文件
|-- filters 過濾器,全局工具
|-- icons 圖標,全局資源
|-- datas 模擬數據,臨時存放
|-- lib 外部引用的插件存放及修改文件
|-- mock 模擬接口,臨時存放
|-- router 路由,統一管理
|-- store vuex, 統一管理
|-- views 視圖目錄
| |-- staffWorkbench 視圖模塊名
| |-- |-- staffWorkbench.vue 模塊入口頁面
| |-- |-- indexComponents 模塊頁面級組件文件夾
| |-- |-- components 模塊通用組件文件夾
複製代碼
<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
複製代碼
代碼註釋在一個項目的後期維護中顯的尤其重要,因此咱們要爲每個被複用的組件編寫組件使用說明,爲組件中每個方法編寫方法說明
公共組件使用說明
各組件中重要函數或者類說明
複雜的業務邏輯處理說明
特殊狀況的代碼處理說明,對於代碼中特殊用途的變量、存在臨界值、函數中使用的 hack、使用了某種算法或思路等須要進行註釋描述
多重 if 判斷語句
註釋塊必須以/**(至少兩個星號)開頭**/
單行註釋使用//
註釋單獨一行,不要在代碼後的同一行內加註釋。例如:
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 風格編碼
定義變量使用 let ,定義常量使用 const
靜態字符串一概使用單引號或反引號,動態字符串使用反引號
// 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'
複製代碼
// 數組解構賦值
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 }) {}
複製代碼
拷貝數組
使用擴展運算符(...)拷貝數組。
const items = [1, 2, 3, 4, 5]
// bad
const itemsCopy = items
// good
const itemsCopy = [...items]
複製代碼
箭頭函數
須要使用函數表達式的場合,儘可能用箭頭函數代替。由於這樣更簡潔,並且綁定了 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);
複製代碼
// bad
import * as myObject from './importModule'
// good
import myObject from './importModule'
複製代碼
function makeStyleGuide() {
}
export default makeStyleGuide;
複製代碼
const StyleGuide = {
es6: {
}
};
export default StyleGuide;
複製代碼
// bad
v-bind:class="{'show-left':true}"
v-on:click="getListData"
// good
:class="{'show-left':true}"
@click="getListData"
複製代碼
<!-- 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>
複製代碼
避免 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>
複製代碼
<!-- 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 定義應該儘可能詳細
// bad 這樣作只有開發原型系統時能夠接受
props: ['status']
// good
props: {
status: {
type: String,
required: true,
validator: function (value) {
return [
'syncing',
'synced',
'version-conflict',
'error'
].indexOf(value) !== -1
}
}
}
複製代碼
避免 this.$parent
調試信息 console.log() debugger 使用完及時刪除
除了三目運算,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);
複製代碼
統一使用"-"連字符
省略值爲 0 時的單位
// bad
padding-bottom: 0px;
margin: 0em;
// good
padding-bottom: 0;
margin: 0;
複製代碼
若是 CSS 能夠作到,就不要使用 JS
建議並適當縮寫值,提升可讀性,特殊狀況除外
「建議並適當」是由於縮寫老是會包含一系列的值,而有時候咱們並不但願設置某一值,反而形成了麻煩,那麼這時候你能夠不縮寫,而是分開寫。
固然,在一切能夠縮寫的狀況下,請務必縮寫,它最大的好處就是節省了字節,便於維護,並使閱讀更加一目瞭然。
// 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;
}
複製代碼
左到右,從上到下
顯示屬性 | 自身屬性 | 文本屬性和其餘修飾 |
---|---|---|
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;
}
複製代碼
元素選擇器應該避免在 scoped 中出現
官方文檔說明:在 scoped 樣式中,類選擇器比元素選擇器更好,由於大量使用元素選擇器是很慢的。
分類的命名方法
使用單個字母加上"-"爲前綴
佈局(grid)(.g-);
模塊(module)(.m-);
元件(unit)(.u-);
功能(function)(.f-);
皮膚(skin)(.s-);
狀態(.z-)。
統一語義理解和命名
佈局(.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 的嵌套功能的時候,重要的是有一個明確的嵌套順序,如下內容是一個 SCSS 塊應具備的順序。
.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;
}
}
}
複製代碼
<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>
複製代碼