本文檔為前端 vue 開發規范
為提高團隊協作效率
便于后臺人員添加功能及前端后期優化維護
輸出高質量的文檔
為了讓大家書寫可維護的代碼,而不是一次性的代碼
讓團隊當中其他人看你的代碼能一目了然
甚至一段時間時候后你再看你某個時候寫的代碼也能看
const MAX_COUNT=10
const URL='https://www.baidu.com/'
復制代碼
官方文檔推薦及使用遵循規則:
PascalCase (單詞首字母大寫命名)是最通用的聲明約定
kebab-case (短橫線分隔命名) 是最通用的使用約定
//bad
go、nextPage、show、open、login
// good
jumpPage、openCarInfoDialog
復制代碼
//bad
takeData、confirmData、getList、postForm
// good
getListData、postFormData
復制代碼
附: 函數方法常用的動詞:
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 聚集
復制代碼
在聲明 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>
復制代碼
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
復制代碼
代碼注釋在一個項目的后期維護中顯得尤為重要,所以我們要為每一個被復用的組件編寫組件使用說明,為組件中每一個方法編寫方法說明
注釋單獨一行,不要在代碼后的同一行內加注釋。例如:
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 風格編碼
// 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]
復制代碼
// 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>
復制代碼
<!-- 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
}
}
}
復制代碼
// bad
if (true)
alert(name);
console.log(name);
// bad
if (true)
alert(name);
console.log(name)
// good
if (true) {
alert(name);
}
console.log(name);
復制代碼
// bad
padding-bottom: 0px;
margin: 0em;
// good
padding-bottom: 0;
margin: 0;
復制代碼
// 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;
}
復制代碼
布局(.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 |
.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;
}
}
}
復制代碼
使用自閉合標簽的寫法 小寫加下劃線
<template>
<my-owner-components />
</template>
為提高可讀性 組件應用時換行 按照 ref、class、傳入、傳出 順序書寫
<template>
<my-components
ref="myComponents"
class="home-my-components"
:data="data"
@changeHandle="changeHandle"
/>
</template>
在模版中 簡單情況使用表達式 復雜情況使用計算屬性或函數
<template>
<!-- 簡單情況 -->
<div v-show="data.type===1">
...
</div>
<!-- 復雜情況 -->
<div v-show="getTypeShow(data)">
...
</div>
</template>
<script>
export default {
methods: {
/**
* ***顯示判斷
* @param data **
*/
getTypeShow(data) {
return data.type===1 && ...
}
}
}
</script>
避免過多重復代碼 果超過三行類似的代碼 配置數據再循環遍歷
根據元素嵌套規范 每個塊狀元素獨立一行 內聯元素可選
<template>
<!-- 情況1 -->
<div>
<h1></h1>
<p></p>
<p><span></span><span></span></p>
</div>
<!-- 情況2 -->
<div>
<h1></h1>
<p></p>
<p>
<span></span>
<span></span>
</p>
</div>
</template>
v-show 不會改變dom樹 不會導致重新渲染 用于頻繁的切換顯示隱藏
v-if 會改變dom樹 會導致重新渲染 用于只控制一次顯示隱藏
<template>
<!-- 標簽注釋 -->
<div>
...
</div>
<!-- 組件注釋 -->
<my-owner-components />
</template>
CSS 屬性書寫順序 先決定定位寬高顯示大小 再做局部細節修飾
定位屬性(或顯示屬性 display)=> 寬高屬性=> 邊距屬性(margin padding)=> 背景 顏色 字體等修飾屬性的定義 這樣定義為了更好的可讀性 讓別人只要看一眼就能在腦海中浮現最終顯示的效果
.class-name {
position: fixed;
top: 100px;
left: 0;
right: 0;
bottom: 0;
display: block;
width: 100%;
height: 100%;
margin: 10px;
padding: 10px;
background-color: red;
border-radius: 2px;
font-size: 14px;
color: #000;
line-height: 1.42;
}
組件內部需要覆蓋UI框架樣式 必須在最外層組件加類名
<template>
<div class="input-container">
<el-input class="name-input"></el-input>
</div>
</template>
<style lang="scss">
.input-container {
.name-input {
.el-input__inner {
font-size: 16px;
}
}
}
</style>
以 / 注釋內容 / 格式注釋 前后空格 嵌套子類需要一個回車分割開
/* 注釋內容 */
.class-name {
width: 20px;
/* 這里需要換行 */
.class-name-l {
color: blue
}
}
<script>
export default {
name: 'ExampleName', // 這個名字推薦:大寫字母開頭駝峰法命名
props: {}, // Props 定義
components: {}, // 組件定義
directives: {}, // 指令定義
mixins: [], // 混入 Mixin 定義。
data () { // Data 定義。
return {
dataProps: '' // Data 屬性的每一個變量都需要在后面寫注釋說明用途,就像這樣
}
},
computed: {}, // 計算屬性定義。
watch: {}, // 屬性變化監聽器。
created () {}, // 生命鉤子函數,按照他們調用的順序。
mounted () {}, // 掛載到元素。
activated () {}, // 使用 keep-alive 包裹的組件激活觸發的鉤子函數。
deactivated () {}, // 使用 keep-alive 包裹的組件離開時觸發的鉤子函數
methods: { // 組件方法定義。
publicbFunction () {} // 公共方法的定義,可以提供外面使用
_privateFunction () {} // 私有方法,下劃線定義,僅供組件內使用。多單詞,注意與系統名字沖突!
}
}
</script>
函數/方法注釋必須包含函數說明,有參數和返回值時必須使用注釋標識,它的作者, 依賴關系和兼容性信息。
// 注釋
const userID=24
const userID=12 // 注釋
/*
* 針對下方代碼的說明
* 第一行太長寫第二行
*/
const aa=1
/**
* @Description 加入購物車
* @Author luochen_ya
* @Date 2024-03-13
* @param {Number} goodId 商品id
* @param {Array<Number>} specs sku規格
* @param {Number} amount 數量
* @param {String} remarks 備注
* @returns <Promise> 購物車信息
*/
apiProductAddCard=(goodId, specs, amount, remarks)=> {
return axios.post('***', { goodId, specs, amount, remarks })
}
/**
* @Description: 文件描述
* @Author: luochen_ya
* @Date: 2024-03-13
*/
按照小駝峰命名 首字母小寫
圖片就是img開頭 圖標就是icon開頭
method 方法命名不同于文件命名,盡量完整英文命名,語義表達需完整清楚
<script>
export default {
methods: { // 組件方法定義
publicbFunction () {} // 公共方法的定義 可以提供外面使用
_privateFunction () {} // 私有方法 下劃線定義 僅供組件內使用
}
}
</script>
import MyOwnerComponents from '@/components/MyOwnerComponents'
let userName='luochen_ya'
const userInfo={
name: 'luochen_ya',
age: 24
}
const Constant={
// 公用狀態
COMMON_STATUS_ENABLE=1, // 啟用
COMMON_STATUS_DISABLE=2, // 停用
}
class命名以小寫字母開頭 小寫字母、中劃線和數字組成 以下是一些常用到的 class的名字
├── api 所有api接口
├── assets 靜態資源
│ ├── fonts 全局公用字體
│ ├── icons 全局公用圖標
│ ├── images 全局公用圖片
│ └── styles 全局公用樣式
├── components 公用組件
│ ├── base 基礎組件
│ └── business 業務組件
├── constants 常量 統一管理
├── locales 多語言管理
├── plugins 插件 統一管理
├── router 路由 統一管理
│ └── index.js
├── store vuex 統一管理
│ ├── modules
│ ├── getters.js
│ └── index.js
├── utils 工具函數 統一管理
├── views 視圖目錄(所有業務邏輯的頁面)
可以直接使用eslint 強制統一代碼規范 還能規避一些語法錯誤 或者按照以下自己定義的去配置eslint來使用
以下是個人習慣 僅供參考
頁的生命周期長的,更需要特別注意后期的可維護性。「欲求其上而得中,欲求其中而得下」
https://www.kwgg2020.com/
頁面語言lang
推薦使用屬性值 cmn-Hans-CN(簡體, 中國大陸),
但是考慮瀏覽器和操作系統的兼容性,目前仍然使用 zh-CN 屬性值 <html lang="zh-CN">
lang="en" 表示此頁面定位為英文網頁,這都是給搜索引擎看的,
你的站點是中文站,對html本身不會有影響,現在都講究html規范,你的頁面越規范,就越容易被收錄
細節決定成敗,耐心鑄造不朽
//html 標簽
標簽必須合法且閉合、嵌套正確,標簽名需小寫
標簽語法無錯誤,需要符合語義化
標簽的自定義屬性以data-開頭,如:<a href="#" data-num='18'></a>
除非有特定的功能、組件要求等,禁止隨意使用id來定義元素樣式
//鏈接
給 <a> 標簽加上title屬性
<a>標簽的href屬性必須寫上鏈接地址,暫無的加上javascript:alert('敬請期待!')
非本專題的頁面間跳轉,采用打開新窗口模式:target="_blank"
//https協議自適應
//將調用靜態域名 ossweb-img.qq.com 以及 game.gtimg.cn 的外部請求,
//寫法上一律去掉協議http:部分,采用自適應的寫法。具體方法如下:
<style>
.bg{background: url(//game.gtimg.cn/images/cf/cp/a20161021sqjs/hd.jpg) no-repeat;}
</style>
//鏈接URL
<a href="//cf.qq.com/main.shtml">進入官網</a>
//圖片SRC
<img src="//game.gtimg.cn/images/logo.png">
//JS鏈接
<script src="//ossweb-img.qq.com/images/js/title.js"></script>
//flash
頁面禁止使用flash,動畫使用video,css3,canvas等,低版本瀏覽器使用背景圖片降級。
//選擇器
CSS類名命名
禁止使用層級過深的選擇器,最多3級。
除非有特定的功能、組件要求等,禁止隨意使用id來定義元素樣式
除非是樣式reset需要,禁止對純元素選擇器設置特定樣式,避免樣式污染
//reset.css
a, img {-webkit-touch-callout: none; /* 禁止長按鏈接與圖片彈出菜單 */}
html, body {
-webkit-user-select: none; /* 禁止選中文本(如無文本選中需求,此為必選項) */
user-select: none;
}
//移動端字體
移動端頁面不支持微軟雅黑,宋體等中文字體,終端瀏覽器字體取決于設備上的系統字體。
那么在移動端h5如何定義字體呢font-family呢,一般會用@font-face定義微軟雅黑字體并
存到web服務器上,在需要使用時被自動下載,但這樣操作很消耗用戶流量
//##ios系統
默認中文字體是Heiti SC
默認英文字體是Helvetica
默認數字字體是HelveticaNeue
無微軟雅黑字體
//##android 系統
默認中文字體是Droidsansfallback
默認英文和數字字體是Droid Sans
無微軟雅黑字體
//各個手機都有自己的默認字體,一般不支持我們常用字體,比如微軟雅黑等,
除非特殊要求,一般手機無需定義中文字體,使用系統默認即可。
英文和數字字體可以使用 Helvetica都支持。
/* 移動端定義字體的代碼 */
body{font-family:Helvetica;}
//圖片優化
圖片體積不能超過300K
JPG圖片必須壓縮,一般80%品質即可,保證文字清晰
JPG圖片必須使用漸進式圖片:使用Photoshop的“存儲為web所用格式”時候,勾選“連續”
透明PNG圖片必須使用壓縮工具壓縮后提供
//圖片標簽
PC端img圖片必須填寫width、height、alt屬性
移動端必須填寫alt屬性
alt不能為無意義字符,需要能表現出圖片的含義,如圖片為道具圖,則應該為道具的名稱
//合理切圖
裝飾性圖片合并成精靈圖,減少頁面請求
*請認真填寫需求信息,我們會在24小時內與您取得聯系。