优先级A 必要的(规避错误)
- 这些规则会帮你规避错误,所以学习并接受它们带来的全部代价吧。这里面可能存在例外,但应该非常少,且只有你同时精通 JavaScript 和 Vue 才可以这样做。
优先级B 强烈推荐(增强可读性)
- 这些规则能够在绝大多数工程中改善可读性和开发体验。即使你违反了,代码还是能照常运行,但例外应该尽可能少且有合理的理由。
优先级C 推荐(将选择和认知成本最小化)
- 当存在多个同样好的选项,选任意一个都可以确保一致性。在这些规则里,我们描述了每个选项并建议一个默认的选择。也就是说只要保持一致且理由充分,你可以随意在你的代码库中做出不同的选择。请务必给出一个好的理由!通过接受社区的标准,你将会:
- 训练你的大脑,以便更容易的处理你在社区遇到的代码;
- 不做修改就可以直接复制粘贴社区的代码示例;
- 能够经常招聘到和你编码习惯相同的新人,至少跟 Vue 相关的东西是这样的。
优先级D 谨慎使用(有潜在危险)
- 有些 Vue 特性的存在是为了照顾极端情况或帮助老代码的平稳迁移。当被过度使用时,这些特性会让你的代码难于维护甚至变成 bug 的来源。这些规则是为了给有潜在风险的特性敲个警钟,并说明它们什么时候不应该使用以及为什么。
组件数据(A)
- 当在组件中使用 data property 的时候 (除了 new Vue 外的任何地方),它的值必须是返回一个对象的函数。
export default {
data () {
return {
foo: 'bar'
}
}
}
Prop 定义(A)
props: {
status: {
type: String,
required: true,
default: 'test'
}
}
v-for 必须设置 key(A)
<li
v-for="(item, index) in todos"
:key="todo.id"
>
{{ todo.text }}
</li>
永远不要把 v-if 和 v-for 同时用在同一个元素上(A)
<ul v-if="shouldShowUsers">
<li
v-for="user in users"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
为组件样式设置作用域(A)
<template>
<button class="button button-close">X</button>
</template>
<!-- 使用 `scoped` attribute -->
<style scoped>
.button {
border: none;
border-radius: 2px;
}
.button-close {
background-color: red;
}
</style>
私有 property 名(A)
- 使用模块作用域保持不允许外部访问的函数的私有性。如果无法做到这一点,就始终为插件、混入等不考虑作为对外公共 API 的自定义私有 property 使用 $_ 前缀。并附带一个命名空间以回避和其它作者的冲突 (比如 $yourPluginName)。
var myGreatMixin = {
// ...
methods: {
$_myGreatMixin_update: function () {
// ...
}
}
}
组件文件(B)
- 只要有能够拼接文件的构建系统,就把每个组件单独分成文件。
components/
|- TodoList.js
|- TodoItem.js
components/
|- TodoList.vue
|- TodoItem.vue
但文件组件文件的大小写(B)
- 单文件组件的文件名应该要么始终是单词大写开头 (PascalCase),要么始终是横线连接 (kebab-case)。
- 单词大写开头对于代码编辑器的自动补全最为友好,因为这使得我们在 JS(X) 和模板中引用组件的方式尽可能的一致。然而,混用文件命名方式有的时候会导致大小写不敏感的文件系统的问题,这也是横线连接命名同样完全可取的原因。
components/
|- MyComponent.vue
components/
|- my-component.vue
基础组件名(B)
- 应用特定样式和约定的基础组件 (也就是展示类的、无逻辑的或无状态的组件) 应该全部以一个特定的前缀开头,比如 Base、App 或 V等。
components/
|- BaseButton.vue
|- BaseTable.vue
|- BaseIcon.vue
components/
|- AppButton.vue
|- AppTable.vue
|- AppIcon.vue
components/
|- VButton.vue
|- VTable.vue
|- VIcon.vue
单例组件名(B)
- 只应该拥有单个活跃实例的组件应该以 The 前缀命名,以示其唯一性。
- 这不意味着组件只可用于一个单页面,而是每个页面只使用一次。这些组件永远不接受任何 prop,因为它们是为你的应用定制的,而不是它们在你的应用中的上下文。如果你发现有必要添加 prop,那就表明这实际上是一个可复用的组件,只是目前在每个页面里只使用一次。
components/
|- TheHeading.vue
|- TheSidebar.vue
紧密耦合的组件名(B)
- 和父组件紧密耦合的子组件应该以父组件名作为前缀命名。
- 如果一个组件只在某个父组件的场景下有意义,这层关系应该体现在其名字上。因为编辑器通常会按字母顺序组织文件,所以这样做可以把相关联的文件排在一起。
components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue
components/
|- SearchSidebar.vue
|- SearchSidebarNavigation.vue
组件名中单词顺序(B)
- 组件名应该以高级别的 (通常是一般化/功能性描述的) 单词开头,以描述性的修饰词结尾。
components/
|- SearchButtonClear.vue
|- SearchButtonRun.vue
|- SearchInputQuery.vue
|- SearchInputExcludeGlob.vue
|- SettingsCheckboxTerms.vue
|- SettingsCheckboxLaunchOnStartup.vue
自闭合组件(B)
- 在单文件组件、字符串模板和 JSX 中没有内容的组件应该是自闭合的——但在 DOM 模板里永远不要这样做。
- 自闭合组件表示它们不仅没有内容,而且刻意没有内容。其不同之处就好像书上的一页白纸对比贴有“本页有意留白”标签的白纸。而且没有了额外的闭合标签,你的代码也更简洁。
- 不幸的是,HTML 并不支持自闭合的自定义元素——只有官方的“空”元素。所以上述策略仅适用于进入 DOM 之前 Vue 的模板编译器能够触达的地方,然后再产出符合 DOM 规范的 HTML。
<!-- 在单文件组件、字符串模板和 JSX 中 -->
<MyComponent/>
<!-- 在 DOM 模板中 -->
<my-component></my-component>
模版中的组件名大小写(B)
- 对于绝大多数项目来说,在单文件组件和字符串模板中组件名应该总是 PascalCase 的——但是在 DOM 模板中总是 kebab-case 的。
- PascalCase 相比 kebab-case 有一些优势:
- 1、编辑器可以在模板里自动补全组件名,因为 PascalCase 同样适用于 JavaScript。
- 2、MyComponent 视觉上比 my-component 更能够和单个单词的 HTML 元素区别开来,因为前者的不同之处有两个大写字母,后者只有一个横线。
- 3、如果你在模板中使用任何非 Vue 的自定义元素,比如一个 Web Component,PascalCase 确保了你的 Vue 组件在视觉上仍然是易识别的。
- 不幸的是,由于 HTML 是大小写不敏感的,在 DOM 模板中必须仍使用 kebab-case。
- 还请注意,如果你已经是 kebab-case 的重度用户,那么与 HTML 保持一致的命名约定且在多个项目中保持相同的大小写规则就可能比上述优势更为重要了。在这些情况下,在所有的地方都使用 kebab-case 同样是可以接受的。
<!-- 在单文件组件和字符串模板中 -->
<MyComponent/>
<!-- 在 DOM 模板中 -->
<my-component></my-component>
<!-- 在所有地方 -->
<my-component></my-component>
JS/JSX 中的组件名大小写(B)
- JS/JSX 中的组件名应该始终是 PascalCase 的,尽管在较为简单的应用中只使用 Vue.component 进行全局组件注册时,可以使用 kebab-case 字符串。
Vue.component('MyComponent', {
// ...
})
Vue.component('my-component', {
// ...
})
import MyComponent from './MyComponent.vue'
export default {
name: 'MyComponent',
// ...
}
完整单词的组件名(B)
- 组件名应该倾向于完整单词而不是缩写。
- 编辑器中的自动补全已经让书写长命名的代价非常之低了,而其带来的明确性却是非常宝贵的。不常用的缩写尤其应该避免。
components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue
Prop 名大小写(B)
- 在声明 prop 的时候,其命名应该始终使用 camelCase,而在模板和 JSX 中应该始终使用 kebab-case。
- 我们单纯的遵循每个语言的约定。在 JavaScript 中更自然的是 camelCase。而在 HTML 中则是 kebab-case。
props: {
greetingText: {
type: String,
required: true,
default: 'test'
}
}
<WelcomeMessage greeting-text="hi"/>
多个 Attribute 的元素(B)
- 多个 attribute 的元素应该分多行撰写,每个 attribute 一行。
- 在 JavaScript 中,用多行分隔对象的多个 property 是很常见的最佳实践,因为这样更易读。模板和 JSX 值得我们做相同的考虑。
<img
src="https://vuejs.org/images/logo.png"
alt="Vue Logo"
>
<MyComponent
foo="a"
bar="b"
baz="c"
/>
模版中简单的表达式(B)
- 组件模板应该只包含简单的表达式,复杂的表达式则应该重构为计算属性或方法。
- 复杂表达式会让你的模板变得不那么声明式。我们应该尽量描述应该出现的是什么,而非如何计算那个值。而且计算属性和方法使得代码可以重用。
<!-- 在模板中 -->
{{ normalizedFullName }}
// 复杂表达式已经移入一个计算属性
computed: {
normalizedFullName: function () {
return this.fullName.split(' ').map(function (word) {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}
}
简单的计算属性(B)
- 应该把复杂计算属性分割为尽可能多的更简单的 property。
computed: {
basePrice: function () {
return this.manufactureCost / (1 - this.profitMargin)
},
discount: function () {
return this.basePrice * (this.discountPercent || 0)
},
finalPrice: function () {
return this.basePrice - this.discount
}
}
带引号的 Attribute 值(B)
- 非空 HTML attribute 值应该始终带引号 (单引号或双引号,以 JS 中未使用的为准)。
- 在 HTML 中不带空格的 attribute 值是可以没有引号的,但这鼓励了大家在特征值里不写空格,导致可读性变差。
<input type="text">
<AppSidebar :style="{ width: sidebarWidth + 'px' }">
指令缩写(B)
- 指令缩写 (用 : 表示 v-bind:、用 @ 表示 v-on: 和用 # 表示 v-slot:) 应该要么都用要么都不用。
<input
:value="newTodoText"
:placeholder="newTodoInstructions"
>
<input
v-bind:value="newTodoText"
v-bind:placeholder="newTodoInstructions"
>
<input
@input="onInput"
@focus="onFocus"
>
<input
v-on:input="onInput"
v-on:focus="onFocus"
>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
<template #header>
<h1>Here might be a page title</h1>
</template>
<template #footer>
<p>Here's some contact info</p>
</template>
组件/实例的选项顺序(C)
- 组件/实例的选项应该有统一的顺序。
- 是我们推荐的组件选项默认顺序。它们被划分为几大类,所以你也能知道从插件里添加的新 property 应该放到哪里。
- 1、副作用 (触发组件外的影响)
- 2、全局感知 (要求组件以外的知识)
- 3、组件类型 (更改组件的类型)
- 4、模板修改器 (改变模板的编译方式)
- 5、模板依赖 (模板内使用的资源)
- components
- directives
- filters
- 6、组合 (向选项里合并 property)
- 7、接口 (组件的接口)
- inheritAttrs
- model
- props / propsData
- 8、本地状态 (本地的响应式 property)
- 9、事件 (通过响应式事件触发的回调)
- watch
- 生命周期钩子 (按照它们被调用的顺序)
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- activated
- deactivated
- beforeDestroy
- destroyed
- 10、非响应式的 property (不依赖响应系统的实例 property)
- 11、渲染 (组件输出的声明式描述)
- template / render
- renderError
元素 attribute 的顺序(C)
- 元素 (包括组件) 的 attribute 应该有统一的顺序。
- 这是我们为组件选项推荐的默认顺序。它们被划分为几大类,所以你也能知道新添加的自定义 attribute 和指令应该放到哪里。
- 1、定义 (提供组件的选项)
- 2、列表渲染 (创建多个变化的相同元素)
- 3、条件渲染 (元素是否渲染/显示)
- v-if
- v-if-else
- v-else
- v-show
- v-cloak
- 4、渲染方式 (改变元素的渲染方式)
- 5、全局感知 (需要超越组件的知识)
- 6、唯一的 attribute (需要唯一值的 attribute)
- 7、双向绑定 (把绑定和事件结合起来)
- 8、其它 attribute (所有普通的绑定或未绑定的 attribute)
- 9、事件 (组件事件监听器)
- 10、内容 (覆写元素的内容)
组件/事例选项中的空行(C)
- 你可能想在多个 property 之间增加一个空行,特别是在这些选项一屏放不下,需要滚动才能都看到的时候。
- 当你的组件开始觉得密集或难以阅读时,在多个 property 之间添加空行可以让其变得容易。在一些诸如 Vim 的编辑器里,这样格式化后的选项还能通过键盘被快速导航。
props: {
value: {
type: String,
required: true
},
focused: {
type: Boolean,
default: false
},
label: String,
icon: String
},
computed: {
formattedValue: function () {
// ...
},
inputClasses: function () {
// ...
}
}
// 没有空行在组件易于阅读和导航时也没问题。
props: {
value: {
type: String,
required: true
},
focused: {
type: Boolean,
default: false
},
label: String,
icon: String
},
computed: {
formattedValue: function () {
// ...
},
inputClasses: function () {
// ...
}
}
但文件组件的顶级元素顺序(C)
- 单文件组件应该总是让 template、script 和 style 标签的顺序保持一致。且 style 要放在最后,因为另外两个标签至少要有一个。
<!-- ComponentA.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>
<!-- ComponentB.vue -->
<script>/* ... */</script>
<template>...</template>
<style>/* ... */</style>
<!-- ComponentA.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>
<!-- ComponentB.vue -->
<template>...</template>
<script>/* ... */</script>
<style>/* ... */</style>
没有在 v-if/v-else-if/v-else 中使用 key(D)
- 如果一组 v-if + v-else 的元素类型相同,最好使用 key (比如两个 div 元素)。
- 默认情况下,Vue 会尽可能高效的更新 DOM。这意味着其在相同类型的元素之间切换时,会修补已存在的元素,而不是将旧的元素移除然后在同一位置添加一个新元素。如果本不相同的元素被识别为相同,则会出现意料之外的结果。
// 反例
<div v-if="error">
错误:{{ error }}
</div>
<div v-else>
{{ results }}
</div>
// 好例
<div
v-if="error"
key="search-status"
>
错误:{{ error }}
</div>
<div
v-else
key="search-results"
>
{{ results }}
</div>
scoped 中的元素选择器(D)
- 元素选择器应该避免在 scoped 中出现。
- 在 scoped 样式中,类选择器比元素选择器更好,因为大量使用元素选择器是很慢的。
// 反例
<template>
<button>X</button>
</template>
<style scoped>
button {
background-color: red;
}
</style>
// 好例
<template>
<button class="btn btn-close">X</button>
</template>
<style scoped>
.btn-close {
background-color: red;
}
</style>
隐性的父子组件通信(D)
- 应该优先通过 prop 和事件进行父子组件之间的通信,而不是 this.$parent 或变更 prop。
- 一个理想的 Vue 应用是 prop 向下传递,事件向上传递的。遵循这一约定会让你的组件更易于理解。然而,在一些边界情况下 prop 的变更或 this.$parent 能够简化两个深度耦合的组件。
- 问题在于,这种做法在很多简单的场景下可能会更方便。但请当心,不要为了一时方便 (少写代码) 而牺牲数据流向的简洁性 (易于理解)。
// 反例
Vue.component('TodoItem', {
props: {
todo: {
type: Object,
required: true
}
},
template: '<input v-model="todo.text">'
})
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>
`
})
// 好例
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
}
},
template: `
<span>
{{ todo.text }}
<button @click="$emit('delete')">
X
</button>
</span>
`
})
非 Flux 的全局状态管理(D)
- 应该优先通过 Vuex 管理全局状态,而不是通过 this.$root 或一个全局事件总线。
- 通过 this.$root 和/或全局事件总线管理状态在很多简单的情况下都是很方便的,但是并不适用于绝大多数的应用。
- Vuex 是 Vue 的官方类 flux 实现,其提供的不仅是一个管理状态的中心区域,还是组织、追踪和调试状态变更的好工具。它很好地集成在了 Vue 生态系统之中 (包括完整的 Vue DevTools 支持)。
// 反例
// 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
})
}
}
})
// 好例
// 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>