了解 Vue 官方的风格指南是 Vue 开发者必备的知识。这份指南提供了编写可维护、一致且高效的 Vue 代码的最佳实践。以下是一些重要的规则分类和具体示例:
🔥 优先级 A:必要的规则(规避错误)
1. 组件命名
- 多词组件名:避免与 HTML 元素冲突
// 👍 推荐
export default {
name: 'TodoItem'
}
// 👎 不推荐
export default {
name: 'Todo'
}
2. Prop 定义
- 详细定义 Prop:提供类型和验证
// 👍 推荐
props: {
status: {
type: String,
required: true,
validator: value => ['success', 'warning', 'danger'].includes(value)
}
}
// 👎 不推荐
props: ['status']
3. v-for 设置 key
- 总是使用 key
<!-- 👍 推荐 -->
<li v-for="todo in todos" :key="todo.id">
{{ todo.text }}
</li>
<!-- 👎 不推荐 -->
<li v-for="todo in todos">
{{ todo.text }}
</li>
4. 避免 v-if 和 v-for 一起使用
<!-- 👍 推荐 -->
<ul>
<li v-for="user in activeUsers" :key="user.id">
{{ user.name }}
</li>
</ul>
<!-- 👎 不推荐 -->
<ul>
<li v-for="user in users" v-if="user.isActive" :key="user.id">
{{ user.name }}
</li>
</ul>
⚡ 优先级 B:强烈推荐的规则
5. 组件文件命名
- 单文件组件使用 PascalCase 或 kebab-case
// 👍 推荐
MyComponent.vue 或 my-component.vue
// 👎 不推荐
myComponent.vue
6. 紧密耦合的组件名
- 子组件以父组件名作为前缀
// 👍 推荐
components/
|- TodoList.vue
|- TodoListItem.vue
|- TodoListItemButton.vue
// 👎 不推荐
components/
|- TodoList.vue
|- TodoItem.vue
|- TodoButton.vue
7. 自闭合组件
<!-- 👍 推荐 -->
<MyComponent />
<my-component />
<!-- 👎 不推荐 -->
<MyComponent></MyComponent>
8. 模板中简单的表达式
<!-- 👍 推荐 -->
{{
fullName.split(' ').map(word => {
return word[0].toUpperCase() + word.slice(1)
}).join(' ')
}}
<!-- 👎 不推荐(复杂逻辑放在模板中) -->
{{
fullName.split(' ').map(function (word) {
if (word) {
return word[0].toUpperCase() + word.slice(1)
} else {
return ''
}
}).join(' ')
}}
🎯 优先级 C:推荐的规则
9. 组件选项顺序
export default {
name: 'ExampleComponent',
// 1. 副作用相关
components: {},
directives: {},
// 2. 组合
mixins: [],
provide: {},
inject: {},
// 3. 接口
props: {},
emits: {},
// 4. 本地状态
data() {
return {}
},
computed: {},
// 5. 生命周期
created() {},
mounted() {},
// 6. 方法
methods: {},
// 7. 渲染
template: {},
render() {}
}
10. 元素属性顺序
<!-- 👍 推荐 -->
<template>
<div
is="header"
v-if="visible"
v-model="value"
ref="container"
key="main"
v-my-directive="arg"
id="unique-id"
class="container"
style="color: red"
@click="handleClick"
v-on:keyup="handleKeyup"
/>
</template>
11. 单文件组件顶级元素顺序
<!-- 👍 推荐 -->
<template>...</template>
<script>...</script>
<style>...</style>
💡 其他重要规则
12. 指令缩写
<!-- 👍 推荐 -->
<input :value="value" @input="onInput">
<!-- 👎 不推荐 -->
<input v-bind:value="value" v-on:input="onInput">
13. 计算属性复杂度
// 👍 推荐
computed: {
displayName() {
if (this.user.firstName && this.user.lastName) {
return `${this.user.firstName} ${this.user.lastName}`
} else {
return this.user.username
}
}
}
// 👎 不推荐(过于复杂)
computed: {
transformedData() {
// 包含大量数据处理逻辑...
}
}
14. 简单的 computed 属性
// 👍 推荐
computed: {
basePrice() {
return this.quantity * this.price
},
discount() {
return this.basePrice * this.discountRate
},
finalPrice() {
return this.basePrice - this.discount
}
}
这些规则帮助团队保持代码一致性,提高可维护性,并避免常见的错误模式。在实际项目中,可以通过 ESLint 插件 eslint-plugin-vue
来自动化检查这些规则。
THE END