风格指南
组件 名为多个单词
用户组件名称应始终是多单词,但根组件除外。这可以防止与现有和将来的 HTML 元素发生冲突,因为所有 HTML 元素都是一个单词。
Vue.component('todo-item', {
// ...
})
export default {
name: 'TodoItem',
// ...
}
prop 使用详细定义
- prop定义应始终尽可能详细,至少指定类型。
- 在声明期间,prop 名称应始终使用 camelCase。在 DOM 模板中使用时,props 应该是 kebab 大小写的。单文件组件模板和 JSX 可以使用 kebab-case 或 camelCase 属性。大小写应该是一致的 - 如果你选择使用 camelCased props,请确保在你的应用程序中不使用 kebab-cased 的 props
详细的 prop 定义有两个好处:
1.它们记录了组件的 API,以便很容易看到组件的使用方式。
2.在开发过程中,如果组件提供了格式不正确的 props,Vue 会警告你,帮助你发现潜在的错误来源。
props: {
status: String
}
// Even better!
props: {
status: {
type: String,
required: true,
validator: value => {
return [
'syncing',
'synced',
'version-conflict',
'error'
].includes(value)
}
}
}
v-for 使用key
<ul>
<li
v-for="todo in todos"
:key="todo.id"
>
{{ todo.text }}
</li>
</ul>
避免同一个元素上使用 v-if 和 v-for
<ul>
<template v-for="user in users" :key="user.id">
<li v-if="user.isActive">
{{ user.name }}
</li>
</template>
</ul>
组件 范围的样式
<template>
<button class="button button-close">×</button>
</template>
<!-- Using the `scoped` attribute -->
<style scoped>
.button {
border: none;
border-radius: 2px;
}
.button-close {
background-color: red;
}
</style>
<template>
<button :class="[$style.button, $style.buttonClose]">×</button>
</template>
<!-- Using CSS modules -->
<style module>
.button {
border: none;
border-radius: 2px;
}
.buttonClose {
background-color: red;
}
</style>
<template>
<button class="c-Button c-Button--close">×</button>
</template>
<!-- Using the BEM convention -->
<style>
.c-Button {
border: none;
border-radius: 2px;
}
.c-Button--close {
background-color: red;
}
</style>
简单计算属性
复杂的计算属性应该被分割成尽可能多的更简单的属性。
更简单、命名良好的计算属性是:
- 更易于测试
当每个计算属性只包含一个非常简单的表达式,并且依赖项非常少时,编写测试来确认它是否正常工作要容易得多。- 更易于阅读 简化计算属性会强制您为每个值指定一个描述性名称,即使它没有被重用。这使得其他开发人员(以及未来的您)更容易专注于他们关心的代码并弄清楚发生了什么。
- 更能适应不断变化的需求 任何可以命名的值都可能对视图有用。例如,我们可能决定显示一条消息,告诉用户他们节省了多少钱。我们也可能决定计算销售税,但可能会单独显示,而不是作为最终价格的一部分。 小型、集中的计算属性对信息的使用方式所做的假设较少,因此随着需求的变化,需要较少的重构。
computed: {
price() {
const basePrice = this.manufactureCost / (1 - this.profitMargin)
return (
basePrice -
basePrice * (this.discountPercent || 0)
)
}
}
computed: {
basePrice() {
return this.manufactureCost / (1 - this.profitMargin)
},
discount() {
return this.basePrice * (this.discountPercent || 0)
},
finalPrice() {
return this.basePrice - this.discount
}
}