Vue前端開發規範

基於Vue官方風格指南整理javascript

1、強制

1. 組件名爲多個單詞

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

正例:前端

export default {
  name: 'TodoItem',
  // ...
}
複製代碼

反例:vue

export default {
  name: 'Todo',
  // ...
}
複製代碼

2. 組件數據

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

正例:react

// In a .vue file
export default {
  data () {
    return {
      foo: 'bar'
    }
  }
}
// 在一個 Vue 的根實例上直接使用對象是能夠的,
// 由於只存在一個這樣的實例。
new Vue({
  data: {
    foo: 'bar'
  }
})
複製代碼

反例:vuex

export default {
  data: {
    foo: 'bar'
  }
}
複製代碼

3. Prop定義

Prop 定義應該儘可能詳細。
在你提交的代碼中,prop 的定義應該儘可能詳細,至少須要指定其類型。bash

正例:markdown

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>
複製代碼

2、強烈推薦(加強可讀性)

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.vue
components/
|- 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"
>
複製代碼

3、推薦

1. 單文件組件的頂級元素的順序

單文件組件應該老是讓<script>、<template> 和 <style> 標籤的順序保持一致。且 <style> 要放在最後,由於另外兩個標籤至少要有一個。

正例:

<!-- ComponentA.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>
複製代碼

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

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.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進行前端編碼,規定Tab大小爲2個空格

  1. 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
}
複製代碼
  1. vs code 插件
  • Auto Close Tag
  • Path Intellisense
  • Prettier
  • Vetur
  • vscode-icons
相關文章
相關標籤/搜索