# Vue 推荐写法
5.1、组件名为多个单词
我们开发过程中自定义的组件的名称需要为多个单词,这样做可以避免跟现有的以及未来的 HTML 元素相冲突,因为所有的 HTML 元素名称都是单个单词的。
推荐:
Vue.component('todo-item', {
// ...
})
export default {
name: 'TodoItem',
// ...
}
2
3
4
5
6
7
不推荐:
Vue.component('todo', {
// ...
})
export default {
name: 'Todo',
// ...
}
2
3
4
5
6
7
5.2、组件的 data 必须是一个函数 当在组件中使用 data 属性的时候 (除了 new Vue 外的任何地方),它的值必须是返回一个对象的函数。 因为如果直接是一个对象的话,子组件之间的属性值会互相影响。
推荐:
export default {
data () {
return {
foo: 'bar'
}
}
}
2
3
4
5
6
7
不推荐:
export default {
data: {
foo: 'bar'
}
}
2
3
4
5
5.3、Prop 定义应该尽量详细 prop 的定义应该尽量详细,至少需要指定其类型。
推荐:
props: {
status: String
}
// 更好的做法!
props: {
status: {
type: String,
required: true,
validator: function (value) {
return [
'syncing',
'synced',
'version-conflict',
'error'
].indexOf(value) !== -1
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
不推荐:
props: ['status']
5.4、为 v-for 设置键值 v-for 中总是有设置 key 值。在组件上总是必须用 key 配合 v-for,以便维护内部组件及其子树的状态。
推荐:
<ul>
<li
v-for="todo in todos"
:key="todo.id">
{{ todo.text }}
</li>
</ul>
2
3
4
5
6
7
不推荐:
<ul>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ul>
2
3
4
5
5.5、完整单词的组件名 组件名应该倾向于完整单词而不是缩写,编辑器中的自动补全已经让书写长命名的代价非常之低了,而其带来的明确性却是非常宝贵的。不常用的缩写尤其应该避免。
推荐:
components/
|- StudentDashboardSettings.vue
|- UserProfileOptions.vue
2
3
不推荐:
components/
|- SdSettings.vue
|- UProfOpts.vue
2
3
5.6、多个特性元素的每个特性分行 在 JavaScript 中,用多行分隔对象的多个属性是很常见的最佳实践,因为这样更易读。
推荐:
<MyComponent
foo="a"
bar="b"
baz="c"
/>
2
3
4
5
不推荐:
<MyComponent foo="a" bar="b" baz="c"/>
5.7、模板中简单的表达式 组件模板应该只包含简单的表达式,复杂的表达式则应该重构为计算属性或方法。复杂表达式会让你的模板变得不那么声明式。我们应该尽量描述应该出现的是什么,而非如何计算那个值。而且计算属性和方法使得代码可以重用。
推荐:
<!-- 在模板中 -->
{{ normalizedFullName }}
// 复杂表达式已经移入一个计算属性
computed: {
normalizedFullName: function () {
return this.fullName.split(' ').map(function (word) {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}
}
2
3
4
5
6
7
8
9
10
不推荐:
{{
fullName.split(' ').map(function (word) {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}}
2
3
4
5
5.8、简单的计算属性 应该把复杂计算属性分割为尽可能多的更简单的属性。
推荐:
computed: {
basePrice: function () {
return this.manufactureCost / (1 - this.profitMargin)
},
discount: function () {
return this.basePrice * (this.discountPercent || 0)
},
finalPrice: function () {
return this.basePrice - this.discount
}
}
2
3
4
5
6
7
8
9
10
11
不推荐:
computed: {
price: function () {
var basePrice = this.manufactureCost / (1 - this.profitMargin)
return (
basePrice -
basePrice * (this.discountPercent || 0)
)
}
}
2
3
4
5
6
7
8
9
5.9、指令缩写 指令推荐都使用缩写形式,(用 : 表示 v-bind: 、用 @ 表示 v-on: 和用 # 表示 v-slot:)。
推荐:
<input
@input="onInput"
@focus="onFocus"
>
2
3
4
不推荐:
<input
v-on:input="onInput"
@focus="onFocus"
>
2
3
4
5.10、标签顺序保持一致 单文件组件应该总是让标签顺序保持为 、
← TS 推荐写法 React 推荐写法 →