vue 風格指南-必須的

組件名爲多個單詞

組件名應該始終是多個單詞的,根組件 App 以及 <transition><component> 之類的 Vue 內置組件除外。vue

這樣作能夠避免跟現有的以及將來的 HTML 元素相沖突,由於全部的 HTML 元素名稱都是單個單詞的。git

 

組件數據-data

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

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

組件數據-prop

Prop 定義應該儘可能詳細。ide

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

細緻的 prop 定義有兩個好處:ui

  • 它們寫明瞭組件的 API,因此很容易看懂組件的用法;
  • 在開發環境下,若是向一個組件提供格式不正確的 prop,Vue 將會告警,以幫助你捕獲潛在的錯誤來源。

更好的例子spa

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

 

爲 v-for 設置鍵值

避免 v-if 和 v-for 用在一塊兒

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

  • 爲了不渲染本應該被隱藏的列表 (好比 v-for="user in users" v-if="shouldShowUsers")。這種情形下,請將 v-if 移動至容器元素上 (好比 ulol)。component

 

爲組件樣式設置做用域

<template>
  <button class="button button-close">X</button>
</template>

<!-- 使用 `scoped` 特性 -->
<style scoped>
.button {
  border: none;
  border-radius: 2px;
}

.button-close {
  background-color: red;
}
</style>

<template>
  <button :class="[$style.button, $style.buttonClose]">X</button>
</template>

<!-- 使用 CSS Modules -->
<style module>
.button {
  border: none;
  border-radius: 2px;
}

.buttonClose {
  background-color: red;
}
</style>

<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>
相關文章
相關標籤/搜索