国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Vue前端開發規范整理(推薦)

2019-11-19 13:58:15
字體:
來源:轉載
供稿:網友

基于Vue官方風格指南整理

一、強制

1. 組件名為多個單詞

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

正例:

export default { name: 'TodoItem', // ...}反例:export default { name: 'Todo', // ...}

2. 組件數據

組件的 data 必須是一個函數。

當在組件中使用 data 屬性的時候 (除了 new Vue 外的任何地方),它的值必須是返回一個對象的函數。

正例:

// In a .vue fileexport default { data () { return { foo: 'bar' } }}// 在一個 Vue 的根實例上直接使用對象是可以的,// 因為只存在一個這樣的實例。new Vue({ data: { foo: 'bar' }})

反例:

export default { data: { foo: 'bar' }}

3. Prop定義

Prop 定義應該盡量詳細。

在你提交的代碼中,prop 的定義應該盡量詳細,至少需要指定其類型。

正例:

props: { status: String}// 更好的做法!props: { status: { type: String, required: true, validator: function (value) { return [ 'syncing', 'synced', 'version-conflict', 'error' ].indexOf(value) !== -1 } }}

反例:

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

4. 為v-for設置鍵值

總是用 key 配合 v-for。

在組件上_總是_必須用 key 配合 v-for,以便維護內部組件及其子樹的狀態。甚至在元素上維護可預測的行為,比如動畫中的對象固化 (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 用在一起

永遠不要把 v-if 和 v-for 同時用在同一個元素上。

一般我們在兩種常見的情況下會傾向于這樣做:

為了過濾一個列表中的項目 (比如 v-for="user in users" v-if="user.isActive")。在這種情形下,請將 users 替換為一個計算屬性 (比如 activeUsers),讓其返回過濾后的列表。

為了避免渲染本應該被隱藏的列表 (比如 v-for="user in users" v-if="shouldShowUsers")。這種情形下,請將 v-if 移動至容器元素上 (比如 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. 為組件樣式設置作用域

對于應用來說,頂級 App 組件和布局組件中的樣式可以是全局的,但是其它所有組件都應該是有作用域的。

這條規則只和單文件組件有關。你不一定要使用 scoped 特性。設置作用域也可以通過 CSS Modules,那是一個基于 class 的類似 BEM 的策略,當然你也可以使用其它的庫或約定。

不管怎樣,對于組件庫,我們應該更傾向于選用基于 class 的策略而不是 scoped 特性。 

這讓覆寫內部樣式更容易:使用了常人可理解的 class 名稱且沒有太高的選擇器優先級,而且不太會導致沖突。

正例:

<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>

二、強烈推薦(增強可讀性)

1. 組件文件

只要有能夠拼接文件的構建系統,就把每個組件單獨分成文件。
當你需要編輯一個組件或查閱一個組件的用法時,可以更快速的找到它。

正例:

components/|- TodoList.vue|- TodoItem.vue

反例:

Vue.component('TodoList', { // ...})Vue.component('TodoItem', { // ...})

2. 單文件組件文件的大小寫

單文件組件的文件名應該要么始終是單詞大寫開頭 (PascalCase)

正例:

components/|- MyComponent.vue

反例:

components/|- myComponent.vue|- mycomponent.vue

3. 基礎組件名

應用特定樣式和約定的基礎組件 (也就是展示類的、無邏輯的或無狀態的組件) 應該全部以一個特定的前綴開頭,比如 Base、App 或 V。

正例:

components/|- BaseButton.vue|- BaseTable.vue|- BaseIcon.vue

反例:

components/|- MyButton.vue|- VueTable.vue|- Icon.vue

4. 單例組件名

只應該擁有單個活躍實例的組件應該以 The 前綴命名,以示其唯一性。

這不意味著組件只可用于一個單頁面,而是每個頁面只使用一次。這些組件永遠不接受任何 prop,因為它們是為你的應用定制的,而不是它們在你的應用中的上下文。如果你發現有必要添加 prop,那就表明這實際上是一個可復用的組件,只是目前在每個頁面里只使用一次。

正例:

components/|- TheHeading.vue|- TheSidebar.vue

反例:

components/|- Heading.vue|- MySidebar.vue

5. 緊密耦合的組件名

和父組件緊密耦合的子組件應該以父組件名作為前綴命名。

如果一個組件只在某個父組件的場景下有意義,這層關系應該體現在其名字上。因為編輯器通常會按字母順序組織文件,所以這樣做可以把相關聯的文件排在一起。

正例:

components/|- TodoList.vue|- TodoListItem.vue|- TodoListItemButton.vuecomponents/|- SearchSidebar.vue|- SearchSidebarNavigation.vue

反例:

components/|- SearchSidebar.vue|- NavigationForSearchSidebar.vue

6. 組件名中的單詞順序

組件名應該以高級別的 (通常是一般化描述的) 單詞開頭,以描述性的修飾詞結尾。

正例:

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. 完整單詞的組件名

組件名應該傾向于完整單詞而不是縮寫。

正例:

components/|- StudentDashboardSettings.vue|- UserProfileOptions.vue

反例:

components/|- SdSettings.vue|- UProfOpts.vue

9. 多個特性的元素

多個特性的元素應該分多行撰寫,每個特性一行。

正例:

<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. 模板中簡單的表達式

組件模板應該只包含簡單的表達式,復雜的表達式則應該重構為計算屬性或方法。
復雜表達式會讓你的模板變得不那么聲明式。我們應該盡量描述應該出現的是什么,而非如何計算那個值。而且計算屬性和方法使得代碼可以重用。

正例:

<!-- 在模板中 -->{{ normalizedFullName }}// 復雜表達式已經移入一個計算屬性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. 簡單的計算屬性

正例:

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. 帶引號的特性值

非空 HTML 特性值應該始終帶引號 (單引號或雙引號,選你 JS 里不用的那個)。
在 HTML 中不帶空格的特性值是可以沒有引號的,但這樣做常常導致帶空格的特征值被回避,導致其可讀性變差。

正例:

<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. 單文件組件的頂級元素的順序

單文件組件應該總是讓<script>、<template> 和 <style> 標簽的順序保持一致。且 <style> 要放在最后,因為另外兩個標簽至少要有一個。

正例:

<!-- ComponentA.vue --><template>...</template><script>/* ... */</script><style>/* ... */</style>

四、謹慎使用 (有潛在危險的模式)

1. 沒有在 v-if/v-if-else/v-else 中使用 key

如果一組 v-if + v-else 的元素類型相同,最好使用 key (比如兩個 <div> 元素)。

正例:

<div v-if="error" key="search-status"> 錯誤:{{ error }}</div><div v-else key="search-results"> {{ results }}</div>反例:<div v-if="error"> 錯誤:{{ error }}</div><div v-else> {{ results }}</div>

2. scoped 中的元素選擇器

元素選擇器應該避免在 scoped 中出現。

在 scoped 樣式中,類選擇器比元素選擇器更好,因為大量使用元素選擇器是很慢的。

正例:

<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. 隱性的父子組件通信

應該優先通過 prop 和事件進行父子組件之間的通信,而不是 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 的全局狀態管理

應該優先通過 Vuex 管理全局狀態,而不是通過 this.$root 或一個全局事件總線。

正例:

// store/modules/todos.jsexport 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.jsnew 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進行前端編碼,規定Tab大小為2個空格

vs code配置

{ "editor.tabSize": 2, "workbench.startupEditor": "newUntitledFile", "workbench.iconTheme": "vscode-icons", // 以下為stylus配置 "stylusSupremacy.insertColons": false, // 是否插入冒號 "stylusSupremacy.insertSemicolons": false, // 是否插入分好 "stylusSupremacy.insertBraces": false, // 是否插入大括號 "stylusSupremacy.insertNewLineAroundImports": false, // import之后是否換行 "stylusSupremacy.insertNewLineAroundBlocks": false, // 兩個選擇器中是否換行 "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

總結

以上所述是小編給大家介紹的Vue前端開發規范整理,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 都昌县| 舟曲县| 天长市| 克拉玛依市| 修文县| 广昌县| 日喀则市| 霍林郭勒市| 华池县| 珲春市| 正镶白旗| 区。| 定南县| 攀枝花市| 清流县| 镇安县| 红安县| 黄冈市| 尼木县| 松江区| 阿克苏市| 泗水县| 玉屏| 盐亭县| 昌邑市| 靖宇县| 昌都县| 开化县| 长春市| 土默特左旗| 昭觉县| 榆社县| 梧州市| 姚安县| 鸡泽县| 睢宁县| 盐山县| 德格县| 陈巴尔虎旗| 吴桥县| 兰西县|