Vue前端開發(fā)規(guī)范整理(推薦)
基于Vue官方風(fēng)格指南整理
一、強(qiáng)制
1. 組件名為多個(gè)單詞
組件名應(yīng)該始終是多個(gè)單詞的,根組件 App 除外。
正例:
export default {
name: 'TodoItem',
// ...
}
反例:
export default {
name: 'Todo',
// ...
}
2. 組件數(shù)據(jù)
組件的 data 必須是一個(gè)函數(shù)。
當(dāng)在組件中使用 data 屬性的時(shí)候 (除了 new Vue 外的任何地方),它的值必須是返回一個(gè)對(duì)象的函數(shù)。
正例:
// In a .vue file
export default {
data () {
return {
foo: 'bar'
}
}
}
// 在一個(gè) Vue 的根實(shí)例上直接使用對(duì)象是可以的,
// 因?yàn)橹淮嬖谝粋€(gè)這樣的實(shí)例。
new Vue({
data: {
foo: 'bar'
}
})
反例:
export default {
data: {
foo: 'bar'
}
}
3. Prop定義
Prop 定義應(yīng)該盡量詳細(xì)。
在你提交的代碼中,prop 的定義應(yīng)該盡量詳細(xì),至少需要指定其類型。
正例:
props: {
status: String
}
// 更好的做法!
props: {
status: {
type: String,
required: true,
validator: function (value) {
return [
'syncing',
'synced',
'version-conflict',
'error'
].indexOf(value) !== -1
}
}
}
反例:
// 這樣做只有開發(fā)原型系統(tǒng)時(shí)可以接受 props: ['status']
4. 為v-for設(shè)置鍵值
總是用 key 配合 v-for。
在組件上_總是_必須用 key 配合 v-for,以便維護(hù)內(nèi)部組件及其子樹的狀態(tài)。甚至在元素上維護(hù)可預(yù)測(cè)的行為,比如動(dòng)畫中的對(duì)象固化 (object constancy),也是一種好的做法。
正例:
<ul>
<li
v-for="todo in todos"
:key="todo.id"
>
{{ todo.text }}
</li>
</ul>
反例:
<ul>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ul>
5.避免 v-if 和 v-for 用在一起
永遠(yuǎn)不要把 v-if 和 v-for 同時(shí)用在同一個(gè)元素上。
一般我們?cè)趦煞N常見的情況下會(huì)傾向于這樣做:
為了過濾一個(gè)列表中的項(xiàng)目 (比如 v-for="user in users" v-if="user.isActive")。在這種情形下,請(qǐng)將 users 替換為一個(gè)計(jì)算屬性 (比如 activeUsers),讓其返回過濾后的列表。
為了避免渲染本應(yīng)該被隱藏的列表 (比如 v-for="user in users" v-if="shouldShowUsers")。這種情形下,請(qǐng)將 v-if 移動(dòng)至容器元素上 (比如 ul, ol)。
正例:
<ul v-if="shouldShowUsers">
<li
v-for="user in users"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
反例:
<ul>
<li
v-for="user in users"
v-if="shouldShowUsers"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
6. 為組件樣式設(shè)置作用域
對(duì)于應(yīng)用來說,頂級(jí) App 組件和布局組件中的樣式可以是全局的,但是其它所有組件都應(yīng)該是有作用域的。
這條規(guī)則只和單文件組件有關(guān)。你不一定要使用 scoped 特性。設(shè)置作用域也可以通過 CSS Modules,那是一個(gè)基于 class 的類似 BEM 的策略,當(dāng)然你也可以使用其它的庫或約定。
不管怎樣,對(duì)于組件庫,我們應(yīng)該更傾向于選用基于 class 的策略而不是 scoped 特性。
這讓覆寫內(nèi)部樣式更容易:使用了常人可理解的 class 名稱且沒有太高的選擇器優(yōu)先級(jí),而且不太會(huì)導(dǎo)致沖突。
正例:
<template>
<button class="c-Button c-Button--close">X</button>
</template>
<!-- 使用 BEM 約定 -->
<style>
.c-Button {
border: none;
border-radius: 2px;
}
.c-Button--close {
background-color: red;
}
</style>
反例:
<template>
<button class="btn btn-close">X</button>
</template>
<style>
.btn-close {
background-color: red;
}
</style>
<template>
<button class="button button-close">X</button>
</template>
<!-- 使用 `scoped` 特性 -->
<style scoped>
.button {
border: none;
border-radius: 2px;
}
.button-close {
background-color: red;
}
</style>
二、強(qiáng)烈推薦(增強(qiáng)可讀性)
1. 組件文件
只要有能夠拼接文件的構(gòu)建系統(tǒng),就把每個(gè)組件單獨(dú)分成文件。
當(dāng)你需要編輯一個(gè)組件或查閱一個(gè)組件的用法時(shí),可以更快速的找到它。
正例:
components/ |- TodoList.vue |- TodoItem.vue
反例:
V
ue.component('TodoList', {
// ...
})
Vue.component('TodoItem', {
// ...
})
2. 單文件組件文件的大小寫
單文件組件的文件名應(yīng)該要么始終是單詞大寫開頭 (PascalCase)
正例:
components/ |- MyComponent.vue
反例:
components/ |- myComponent.vue |- mycomponent.vue
3. 基礎(chǔ)組件名
應(yīng)用特定樣式和約定的基礎(chǔ)組件 (也就是展示類的、無邏輯的或無狀態(tài)的組件) 應(yīng)該全部以一個(gè)特定的前綴開頭,比如 Base、App 或 V。
正例:
components/ |- BaseButton.vue |- BaseTable.vue |- BaseIcon.vue
反例:
components/ |- MyButton.vue |- VueTable.vue |- Icon.vue
4. 單例組件名
只應(yīng)該擁有單個(gè)活躍實(shí)例的組件應(yīng)該以 The 前綴命名,以示其唯一性。
這不意味著組件只可用于一個(gè)單頁面,而是每個(gè)頁面只使用一次。這些組件永遠(yuǎn)不接受任何 prop,因?yàn)樗鼈兪菫槟愕膽?yīng)用定制的,而不是它們?cè)谀愕膽?yīng)用中的上下文。如果你發(fā)現(xiàn)有必要添加 prop,那就表明這實(shí)際上是一個(gè)可復(fù)用的組件,只是目前在每個(gè)頁面里只使用一次。
正例:
components/ |- TheHeading.vue |- TheSidebar.vue
反例:
components/ |- Heading.vue |- MySidebar.vue
5. 緊密耦合的組件名
和父組件緊密耦合的子組件應(yīng)該以父組件名作為前綴命名。
如果一個(gè)組件只在某個(gè)父組件的場(chǎng)景下有意義,這層關(guān)系應(yīng)該體現(xiàn)在其名字上。因?yàn)榫庉嬈魍ǔ?huì)按字母順序組織文件,所以這樣做可以把相關(guān)聯(lián)的文件排在一起。
正例:
components/ |- TodoList.vue |- TodoListItem.vue |- TodoListItemButton.vue components/ |- SearchSidebar.vue |- SearchSidebarNavigation.vue
反例:
components/ |- SearchSidebar.vue |- NavigationForSearchSidebar.vue
6. 組件名中的單詞順序
組件名應(yīng)該以高級(jí)別的 (通常是一般化描述的) 單詞開頭,以描述性的修飾詞結(jié)尾。
正例:
components/ |- SearchButtonClear.vue |- SearchButtonRun.vue |- SearchInputQuery.vue |- SearchInputExcludeGlob.vue |- SettingsCheckboxTerms.vue |- SettingsCheckboxLaunchOnStartup.vue
反例:
components/ |- ClearSearchButton.vue |- ExcludeFromSearchInput.vue |- LaunchOnStartupCheckbox.vue |- RunSearchButton.vue |- SearchInput.vue |- TermsCheckbox.vue
7. 模板中的組件名大小寫
總是 PascalCase 的
正例:
<!-- 在單文件組件和字符串模板中 --> <MyComponent/>
反例:
<!-- 在單文件組件和字符串模板中 --> <mycomponent/> <!-- 在單文件組件和字符串模板中 --> <myComponent/>
8. 完整單詞的組件名
組件名應(yīng)該傾向于完整單詞而不是縮寫。
正例:
components/ |- StudentDashboardSettings.vue |- UserProfileOptions.vue
反例:
components/ |- SdSettings.vue |- UProfOpts.vue
9. 多個(gè)特性的元素
多個(gè)特性的元素應(yīng)該分多行撰寫,每個(gè)特性一行。
正例:
<img src="https://vuejs.org/images/logo.png" alt="Vue Logo" > <MyComponent foo="a" bar="b" baz="c" />
反例:
<img src="https://vuejs.org/images/logo.png" alt="Vue Logo"> <MyComponent foo="a" bar="b" baz="c"/>
10. 模板中簡(jiǎn)單的表達(dá)式
組件模板應(yīng)該只包含簡(jiǎn)單的表達(dá)式,復(fù)雜的表達(dá)式則應(yīng)該重構(gòu)為計(jì)算屬性或方法。
復(fù)雜表達(dá)式會(huì)讓你的模板變得不那么聲明式。我們應(yīng)該盡量描述應(yīng)該出現(xiàn)的是什么,而非如何計(jì)算那個(gè)值。而且計(jì)算屬性和方法使得代碼可以重用。
正例:
<!-- 在模板中 -->
{{ normalizedFullName }}
// 復(fù)雜表達(dá)式已經(jīng)移入一個(gè)計(jì)算屬性
computed: {
normalizedFullName: function () {
return this.fullName.split(' ').map(function (word) {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}
}
反例:
{{
fullName.split(' ').map(function (word) {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}}
11. 簡(jiǎn)單的計(jì)算屬性
正例:
computed: {
basePrice: function () {
return this.manufactureCost / (1 - this.profitMargin)
},
discount: function () {
return this.basePrice * (this.discountPercent || 0)
},
finalPrice: function () {
return this.basePrice - this.discount
}
}
反例:
computed: {
price: function () {
var basePrice = this.manufactureCost / (1 - this.profitMargin)
return (
basePrice -
basePrice * (this.discountPercent || 0)
)
}
}
12. 帶引號(hào)的特性值
非空 HTML 特性值應(yīng)該始終帶引號(hào) (單引號(hào)或雙引號(hào),選你 JS 里不用的那個(gè))。
在 HTML 中不帶空格的特性值是可以沒有引號(hào)的,但這樣做常常導(dǎo)致帶空格的特征值被回避,導(dǎo)致其可讀性變差。
正例:
<AppSidebar :style="{ width: sidebarWidth + 'px' }">
反例:
<AppSidebar :style={width:sidebarWidth+'px'}>
13. 指令縮寫
都用指令縮寫 (用 : 表示 v-bind: 和用 @ 表示 v-on:)
正例:
<input @input="onInput" @focus="onFocus" >
反例:
<input v-bind:value="newTodoText" :placeholder="newTodoInstructions" >
三、推薦
1. 單文件組件的頂級(jí)元素的順序
單文件組件應(yīng)該總是讓<script>、<template> 和 <style> 標(biāo)簽的順序保持一致。且 <style> 要放在最后,因?yàn)榱硗鈨蓚€(gè)標(biāo)簽至少要有一個(gè)。
正例:
<!-- ComponentA.vue --> <template>...</template> <script>/* ... */</script> <style>/* ... */</style>
四、謹(jǐn)慎使用 (有潛在危險(xiǎn)的模式)
1. 沒有在 v-if/v-if-else/v-else 中使用 key
如果一組 v-if + v-else 的元素類型相同,最好使用 key (比如兩個(gè) <div> 元素)。
正例:
<div
v-if="error"
key="search-status"
>
錯(cuò)誤:{{ error }}
</div>
<div
v-else
key="search-results"
>
{{ results }}
</div>
反例:
<div v-if="error">
錯(cuò)誤:{{ error }}
</div>
<div v-else>
{{ results }}
</div>
2. scoped 中的元素選擇器
元素選擇器應(yīng)該避免在 scoped 中出現(xiàn)。
在 scoped 樣式中,類選擇器比元素選擇器更好,因?yàn)榇罅渴褂迷剡x擇器是很慢的。
正例:
<template>
<button class="btn btn-close">X</button>
</template>
<style scoped>
.btn-close {
background-color: red;
}
</style>
反例:
<template>
<button>X</button>
</template>
<style scoped>
button {
background-color: red;
}
</style>
3. 隱性的父子組件通信
應(yīng)該優(yōu)先通過 prop 和事件進(jìn)行父子組件之間的通信,而不是 this.$parent 或改變 prop。
正例:
Vue.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
template: `
<input
:value="todo.text"
@input="$emit('input', $event.target.value)"
>
`
})
反例:
Vue.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
methods: {
removeTodo () {
var vm = this
vm.$parent.todos = vm.$parent.todos.filter(function (todo) {
return todo.id !== vm.todo.id
})
}
},
template: `
<span>
{{ todo.text }}
<button @click="removeTodo">
X
</button>
</span>
`
})
4. 非 Flux 的全局狀態(tài)管理
應(yīng)該優(yōu)先通過 Vuex 管理全局狀態(tài),而不是通過 this.$root 或一個(gè)全局事件總線。
正例:
// store/modules/todos.js
export default {
state: {
list: []
},
mutations: {
REMOVE_TODO (state, todoId) {
state.list = state.list.filter(todo => todo.id !== todoId)
}
},
actions: {
removeTodo ({ commit, state }, todo) {
commit('REMOVE_TODO', todo.id)
}
}
}
<!-- TodoItem.vue -->
<template>
<span>
{{ todo.text }}
<button @click="removeTodo(todo)">
X
</button>
</span>
</template>
<script>
import { mapActions } from 'vuex'
export default {
props: {
todo: {
type: Object,
required: true
}
},
methods: mapActions(['removeTodo'])
}
</script>
反例:
// main.js
new Vue({
data: {
todos: []
},
created: function () {
this.$on('remove-todo', this.removeTodo)
},
methods: {
removeTodo: function (todo) {
var todoIdToRemove = todo.id
this.todos = this.todos.filter(function (todo) {
return todo.id !== todoIdToRemove
})
}
}
})
附錄
1. 推薦使用vs code進(jìn)行前端編碼,規(guī)定Tab大小為2個(gè)空格
vs code配置
{
"editor.tabSize": 2,
"workbench.startupEditor": "newUntitledFile",
"workbench.iconTheme": "vscode-icons",
// 以下為stylus配置
"stylusSupremacy.insertColons": false, // 是否插入冒號(hào)
"stylusSupremacy.insertSemicolons": false, // 是否插入分好
"stylusSupremacy.insertBraces": false, // 是否插入大括號(hào)
"stylusSupremacy.insertNewLineAroundImports": false, // import之后是否換行
"stylusSupremacy.insertNewLineAroundBlocks": false, // 兩個(gè)選擇器中是否換行
"vetur.format.defaultFormatter.html": "js-beautify-html",
"eslint.autoFixOnSave": true,
"eslint.validate": [
"javascript",
{
"language": "html",
"autoFix": true
},
{
"language": "vue",
"autoFix": true
},
"javascriptreact",
"html",
"vue"
],
"eslint.options": { "plugins": ["html"] },
"prettier.singleQuote": true,
"prettier.semi": false,
"javascript.format.insertSpaceBeforeFunctionParenthesis": false,
"vetur.format.js.InsertSpaceBeforeFunctionParenthesis": false,
"vetur.format.defaultFormatter.js": "prettier",
// "prettier.eslintIntegration": true
}
vs code 插件
- Auto Close Tag
- Path Intellisense
- Prettier
- Vetur
- vscode-icons
總結(jié)
以上所述是小編給大家介紹的Vue前端開發(fā)規(guī)范整理,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
在Vue methods中調(diào)用filters里的過濾器實(shí)例
今天小編就為大家分享一篇在Vue methods中調(diào)用filters里的過濾器實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-08-08
詳解VScode編輯器vue環(huán)境搭建所遇問題解決方案
這篇文章主要介紹了VScode編輯器vue環(huán)境搭建所遇問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
Vue如何通過Vue.prototype定義原型屬性實(shí)現(xiàn)全局變量
在Vue.js開發(fā)中,通過原型屬性為Vue實(shí)例添加全局變量是一種常見做法,使用$前綴命名,可以避免與組件內(nèi)部的數(shù)據(jù)、方法或計(jì)算屬性產(chǎn)生命名沖突,這種方式簡(jiǎn)單有效,確保了變量在所有Vue實(shí)例中的可用性,同時(shí)保持全局作用域的整潔2024-10-10
Vue中引用JSON數(shù)據(jù)的方法小結(jié)
在現(xiàn)代Web開發(fā)中,JSON是一種輕量級(jí)的數(shù)據(jù)交換格式,易于人閱讀和編寫,同時(shí)也易于機(jī)器解析和生成,Vue.js作為一個(gè)流行的前端框架,支持多種方式引入和處理JSON數(shù)據(jù),本文將詳細(xì)介紹幾種在Vue中引用JSON數(shù)據(jù)的方法,需要的朋友可以參考下2024-10-10
關(guān)于應(yīng)用UI組件的移動(dòng)端適配方式
這篇文章主要介紹了關(guān)于應(yīng)用UI組件的移動(dòng)端適配方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Vue中ElementUI分頁組件Pagination的使用方法
這篇文章主要為大家詳細(xì)介紹了Vue中ElementUI分頁組件Pagination的使用,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-05-05
詳解Vue.js項(xiàng)目API、Router配置拆分實(shí)踐
這篇文章主要介紹了詳解Vue.js項(xiàng)目API、Router配置拆分實(shí)踐,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03
警告[vue-router]?Duplicate?named?routes?definition簡(jiǎn)單解決方法
這篇文章主要關(guān)于介紹了警告[vue-router]?Duplicate?named?routes?definition的解決方法,這個(gè)錯(cuò)誤提示是因?yàn)樵赩ue Router中定義了重復(fù)的路由名稱,需要的朋友可以參考下2023-12-12

