【Uniapp】代码规范六:组件化规范

1. 组件目录结构

将所有的组件放在统一的components目录中,并按功能进行分类。例如:

scss 复制代码
src/
└── components/
    ├── common/            // 公共组件
    │   ├── Button.vue
    │   ├── Modal.vue
    │   └── Icon.vue
    ├── user/              // 用户模块相关组件
    │   ├── UserProfile.vue
    │   └── UserList.vue
    ├── product/           // 产品模块相关组件
    │   ├── ProductCard.vue
    │   └── ProductList.vue
  • 建议:每个文件夹下组件数量不宜过多,保证分类清晰。
  • 分层级结构 :根据组件的作用范围进行分类,如common存放通用组件,feature存放特定功能模块的组件。

2. 组件命名

  • 组件文件名 :使用大驼峰命名法(PascalCase),与组件名保持一致,例如UserProfile.vueProductCard.vue

  • 组件名称 :组件的name字段使用大驼峰命名法,保持与文件名一致,方便调试和排查。

  • 命名建议:

    • 使用名词或名词短语,表示组件的功能或内容。
    • 对于复用性高的组件,如ButtonInput,应保持名称简洁明确。
    • 对于特定模块的组件,可以在名称中体现模块名,例如UserListProductCard等。

3. 组件类型划分

根据组件的功能和重用性,划分为以下几类:

  1. 基础组件(Base Components):

    • 这些组件通常是没有业务逻辑的纯UI组件,如ButtonInputIcon等。
    • 命名通常以Base开头,例如BaseButton.vueBaseInput.vue
  2. 业务组件(Business Components):

    • 这些组件与业务逻辑相关,包含特定模块功能,如UserProfile.vueProductCard.vue等。
  3. 页面级组件(Page Components):

    • 页面级别的组件用于构建整个页面,通常在pages目录下管理,并通过路由直接渲染。

4. 组件内结构规范

组件内代码顺序

  • 组件内部代码顺序应保持一致,建议如下顺序:

    1. name:组件名称,方便调试和查错。
    2. props:接收的外部属性。
    3. data:组件内部的状态数据。
    4. computed:计算属性,派生数据。
    5. methods:组件的业务逻辑方法。
    6. watch:监控属性变化。
    7. lifecycle hooks:生命周期钩子函数。
  • 示例:

    js 复制代码
    <script>
    export default {
      name: 'UserProfile',
      props: {
        userId: {
          type: String,
          required: true
        }
      },
      data() {
        return {
          userProfile: null
        };
      },
      computed: {
        formattedName() {
          return this.userProfile ? `${this.userProfile.firstName} ${this.userProfile.lastName}` : '';
        }
      },
      methods: {
        async fetchUserProfile() {
          // 业务逻辑
        }
      },
      mounted() {
        this.fetchUserProfile();
      }
    };
    </script>

Props 规范

  • 类型定义 :在props中定义时,必须明确类型,使用type,并添加required字段来说明该prop是否必需。

  • 默认值 :使用default字段提供默认值。

  • 规范示例:

    js 复制代码
    props: {
      userId: {
        type: String,
        required: true
      },
      isActive: {
        type: Boolean,
        default: false
      },
      options: {
        type: Array,
        default: () => []
      }
    }

5. 组件通信

父子组件通信(Props & Emit)

  • Props :父组件通过props传递数据到子组件,确保父组件控制数据流。

  • Emit :子组件通过$emit通知父组件事件。

  • 示例

    • 父组件传递props:

      js 复制代码
      <UserProfile :userId="userId" @update="handleUpdate" />
    • 子组件emit事件:

      js 复制代码
      this.$emit('update', updatedData);

非父子组件通信(EventBus 或 Vuex)

  • EventBus:使用事件总线进行跨组件的通信,但建议在较大项目中使用Vuex来管理全局状态。
  • Vuex:使用状态管理工具Vuex进行全局状态的管理和数据传递。

6. 组件样式规范

局部样式作用域

  • 使用<style scoped>来确保组件样式局部化,避免样式污染。

  • 示例:

    html 复制代码
    <style scoped>
    .user-profile {
      font-size: 14px;
    }
    </style>

样式命名(BEM命名法)

  • 推荐使用BEM(Block Element Modifier)命名法管理样式。

  • 示例

    html 复制代码
    <template>
      <div class="user-profile">
        <div class="user-profile__header">Header</div>
        <div class="user-profile__body">Body</div>
        <div class="user-profile__footer user-profile__footer--active">Footer</div>
      </div>
    </template>

    Block : user-profile

    Element : user-profile__header, user-profile__body

    Modifier : user-profile__footer--active


7. 组件重用

公共组件

  • 创建公共组件库 :提取项目中复用率高的组件,形成独立的公共组件库,例如Button.vueModal.vue等。
  • 按需加载:通过动态加载或按需引入的方式减少组件加载时的性能开销。

复用方法与逻辑(Mixin)

  • Mixin :对于多个组件之间共享的逻辑,可以使用mixin,实现代码重用。

  • 示例:

    js 复制代码
    export const userMixin = {
      data() {
        return {
          userData: {}
        };
      },
      methods: {
        fetchUserData() {
          // 复用的逻辑
        }
      }
    };

    在组件中使用:

    js 复制代码
    import { userMixin } from '@/mixins/userMixin';
    ​
    export default {
      mixins: [userMixin],
      mounted() {
        this.fetchUserData();
      }
    };

8. 组件性能优化

  • 异步组件 :对于非关键路径的组件,可以使用Vue的异步组件加载功能进行按需加载,减少初始包体积。

    js 复制代码
    const AsyncComponent = () => import('./components/AsyncComponent.vue');
  • 懒加载:图片等资源可以使用懒加载技术,减少页面的初始加载时间。

  • 避免不必要的重渲染 :使用key值优化组件更新,避免无意义的重绘。


9. 组件测试

  • 单元测试: 对每个组件编写单元测试,确保其功能和界面表现正确。使用JestMocha进行测试。

    测试内容 :组件的渲染、props传递、事件触发等。

    js 复制代码
    import { shallowMount } from '@vue/test-utils';
    import UserProfile from '@/components/UserProfile.vue';
    ​
    test('should render user profile', () => {
      const wrapper = shallowMount(UserProfile, {
        propsData: { userId: '123' }
      });
      expect(wrapper.find('.user-profile').exists()).toBe(true);
    });

通过严格遵循这些组件化规范,能够确保代码的模块化、可维护性和重用性,减少项目开发中的复杂性并提升代码质量。

相关推荐
weixin_3823952315 小时前
为小工厂量身打造:本地部署的物料管理系统带缺料计算
前端·制造
__zRainy__15 小时前
解决pnpm v10+不自动构建
前端·pnpm·工程化
猫猫不是喵喵.16 小时前
Vue3 Props 属性
前端·javascript·vue.js
醉城夜风~17 小时前
CSS元素显示模式(display)
前端·css
AI大模型-小华18 小时前
Codex 三方充值快速入门指南
java·前端·数据库·chatgpt·ai编程·codex·chatgpt pro
做前端的娜娜子20 小时前
同一链接实现 PC Web 与移动 H5 自适应
前端·掘金·金石计划
小帅不太帅20 小时前
架构没变、规模没变,DeepSeek V4 Flash 正式版凭什么暴涨 47 分?
前端·aigc·deepseek
jarvisuni20 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
卷福同学1 天前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端