组件名应该始终是多个单词的,根组件 App 以及 、 之类的 Vue 内置组件除外。
Vue.component('todo-item', {
// ...
})
export default {
name: 'TodoItem',
// ...
}
Prop 定义应该尽量详细。
// 更好的做法!
props: {
status: {
type: String,
required: true,
validator: function (value) {
return [
'syncing',
'synced',
'version-conflict',
'error'
].indexOf(value) !== -1
}
}
}
<ul>
<li
v-for="todo in todos"
:key="todo.id"
>
{{ todo.text }}
</li>
</ul>
永远不要把 v-if 和 v-for 同时用在同一个元素上。
<ul v-if="shouldShowUsers">
<li
v-for="user in users"
:key="user.id"
>
{{ user.name }}
</li>
</ul>
这条规则只和单文件组件有关。
<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>
使用模块作用域保持不允许外部访问的函数的私有性。如果无法做到这一点,就始终为插件、混入等不考虑作为对外公共 API 的自定义私有 property 使用 $_ 前缀。并附带一个命名空间以回避和其它作者的冲突 (比如 $yourPluginName)。
// 甚至更好!
var myGreatMixin = {
// ...
methods: {
publicMethod() {
// ...
myPrivateFunction()
}
}
}
function myPrivateFunction() {
// ...
}
export default myGreatMixin
单文件组件的文件名应该要么始终是单词大写开头 (PascalCase),要么始终是横线连接 (kebab-case)。
components/
|- MyComponent.vue
components/
|- my-component.vue
应用特定样式和约定的基础组件 (也就是展示类的、无逻辑的或无状态的组件) 应该全部以一个特定的前缀开头,比如 Base、App 或 V。
和父组件紧密耦合的子组件应该以父组件名作为前缀命名。
components/
|- SearchSidebar.vue
|- SearchSidebarNavigation.vue
组件名应该倾向于完整单词而不是缩写。
components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue
在声明 prop 的时候,其命名应该始终使用 camelCase,而在模板和 JSX 中应该始终使用 kebab-case。
props: {
greetingText: String
}
<WelcomeMessage greeting-text="hi"/>
组件模板应该只包含简单的表达式,复杂的表达式则应该重构为计算属性或方法。
<!-- 在模板中 -->
{{ normalizedFullName }}
// 复杂表达式已经移入一个计算属性
computed: {
normalizedFullName: function () {
return this.fullName.split(' ').map(function (word) {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}
}