Vue3组件代码编写遵循1.0

优秀的Vue组件代码编写应该遵循以下标准:

  1. 组件设计原则

单一职责原则 (Single Responsibility Principle)

  • 每个组件只负责一个功能
  • 保持组件的纯粹性和可复用性
  • 避免组件过于臃肿

开放封闭原则 (Open-Closed Principle)

  • 对扩展开放,对修改封闭
  • 通过props和插槽提供扩展点
  1. 命名规范

组件命名

文件命名

my-component.vue
user-card.vue
date-picker.vue

Props命名

props: {userName: String,      // camelCaseisLoading: Boolean,    // 布尔值用 is/has/can 前缀maxCount: Number,       // 限定范围用 max/min
}
  1. 结构组织

推荐的组件结构

<template><!-- 模板内容 -->
</template><script>
// 1. 导入依赖
import { ref, computed, onMounted } from 'vue'
import ComponentA from './ComponentA.vue'// 2. 组件定义
export default {name: 'MyComponent',// 3. 组件选项components: { ComponentA },props: { /* ... */ },emits: [/* ... */ ],// 4. 组合式API (Composition API)setup(props, { emit }) {// 状态const count = ref(0)// 计算属性const doubleCount = computed(() => count.value * 2)// 方法const increment = () => count.value++// 生命周期onMounted(() => {// 初始化逻辑})// 返回模板中使用的内容return {count,doubleCount,increment}}
}
</script><style scoped>
/* 组件样式 */
</style>
  1. Props设计

Props定义规范

props: {// 基本类型title: String,count: Number,visible: Boolean,// 多种类型value: [String, Number],// 对象/数组(带默认值)user: {type: Object,default: () => ({})},items: {type: Array,default: () => []},// 自定义验证email: {type: String,required: true,validator: (value) => {return /\S+@\S+\.\S+/.test(value)}}
}
  1. 状态管理

响应式数据设计

// Composition API
setup() {// 局部状态const localState = ref('')// 计算属性const computedValue = computed(() => {return localState.value.toUpperCase()})return { localState, computedValue }
}// Options API
data() {return {// 使用有意义的变量名isLoading: false,userList: [],errorMessage: ''}
}
  1. 事件处理

事件命名规范

// 发射事件
emit('update:modelValue', newValue)
emit('item-click', { id, name })
emit('form-submit', formData)// 事件监听
<template><div @click="handleClick"><button @click.stop="handleButtonClick">提交</button></div>
</template>

事件处理方法命名

methods: {// handle + 事件名handleClick(event) {// 处理点击事件},// on + 组件名/功能名onFormSubmit(data) {// 处理表单提交},// 布尔值方法用 is/can/has 前缀isValidEmail(email) {return /\S+@\S+\.\S+/.test(email)}
}
  1. 代码组织最佳实践

按功能模块组织

export default {data() {return {// 表单相关formData: {},formRules: {},// 列表相关tableData: [],pagination: { page: 1, pageSize: 10 },// UI状态loading: false,dialogVisible: false}},computed: {// 表单相关计算属性isFormValid() { /* ... */ },// 列表相关计算属性filteredData() { /* ... */ }},methods: {// 表单方法validateForm() { /* ... */ },resetForm() { /* ... */ },// 列表方法fetchData() { /* ... */ },handlePageChange() { /* ... */ },// UI交互方法showDialog() { /* ... */ },hideDialog() { /* ... */ }}
}
  1. 样式规范

Scoped样式

<style scoped>
/* 使用 scoped 避免样式污染 */
.my-component {/* 使用有意义的类名 */&__header {/* BEM 命名规范 */}&__content {/* 嵌套语法 */}&--disabled {/* 修饰符 */}
}
</style>
  1. 性能优化

合理使用计算属性

// 好的做法 - 使用计算属性缓存结果
computed: {filteredUsers() {return this.users.filter(user => user.age > 18)}
}// 避免 - 在模板中使用复杂表达式
<template><!-- 避免 --><div v-for="user in users.filter(u => u.age > 18)"><!-- 推荐 --><div v-for="user in filteredUsers">
</template>避免不必要的响应式// 静态数据不需要响应式
const STATIC_CONFIG = {apiUrl: 'https://api.example.com',version: '1.0.0'
}export default {data() {return {// 只有需要变化的数据才放入 datadynamicData: []}}
}
  1. 错误处理和边界情况

防御性编程

methods: {async fetchUserData(userId) {try {// 参数检查if (!userId) {throw new Error('User ID is required')}const response = await api.getUser(userId)// 数据检查if (!response.data) {throw new Error('Invalid response data')}this.userData = response.data} catch (error) {console.error('Failed to fetch user data:', error)this.errorMessage = error.message} finally {this.loading = false}}
}
  1. 文档和注释

组件文档

/*** 用户卡片组件* * @component* @example* <UserCard *   :user="userData" *   :show-actions="true" *   @edit="handleEdit" * />*/
export default {name: 'UserCard',props: {/** 用户信息对象 */user: {type: Object,required: true},/** 是否显示操作按钮 */showActions: {type: Boolean,default: false}}
}
  1. 测试友好性

组件应该易于测试

  // 避免在组件中直接调用全局API// 应该通过依赖注入或props传入// 好的做法export default {inject: ['api'], // 依赖注入methods: {async fetchData() {const response = await this.api.getData() // 可测试}}}// 避免import api from '@/api' // 难以测试

遵循这些标准可以编写出高质量、可维护、可测试的Vue组件代码。