Vue/React组件/指令/Hooks封装的基本原则以及示例


一、组件封装原则与示例

Vue组件封装
  1. 核心原则
    单一职责:每个组件只解决一个功能(如分页、过滤表单)
    Props控制输入:通过定义明确的Props接口接收外部数据(类型校验、默认值)
    Emit事件通信:子组件通过$emit向父组件传递动作(如分页切换)
    插槽扩展性:使用<slot>支持内容动态插入(如表格头部自定义按钮)

  2. 示例:分页表格组件

    <!-- TablePagination.vue -->
    <template>
      <div>
        <table>
          <slot name="body" :data="list"></slot>
        </table>
        <div class="pagination">
          <button @click="prevPage">上一页</button>
          <span>{
        
         
         { currentPage }}</span>
          <button @click="nextPage">下一页</button>
        </div>
      </div>
    </template>
    <script setup>
    const props = defineProps({
      data: { type: Array, required: true },
      pageSize: { type: Number, default: 10 }
    });
    const emit = defineEmits(['page-change']);
    const currentPage = ref(1);
    const list = computed(() => 
      props.data.slice((currentPage.value-1)*props.pageSize, currentPage.value*props.pageSize)
    );
    const nextPage = () => { 
      currentPage.value++; 
      emit('page-change', currentPage.value);
    };
    </script>
    

React组件封装
  1. 核心原则
    组合优于继承:通过children属性传递子元素实现布局复用
    受控/非受控模式:支持通过Props完全控制或内部状态管理
    Hooks解耦逻辑:将状态管理抽取到自定义Hook中(如usePagination)

  2. 示例:受控模态框

    // Modal.jsx
    import { useState } from 'react';
    export const Modal = ({ isOpen, onClose, children }) => {
      if (!isOpen) return null;
      return (
        <div className="modal-overlay">
          <div className="modal-content">
            <button onClick={onClose}>×</button>
            {children}
          </div>
        </div>
      );
    };
    

二、指令封装(Vue专属)

核心原则

功能原子化:每个指令仅实现一个交互行为(如自动聚焦、权限控制)
生命周期绑定:通过mountedupdated等钩子实现动态响应

示例:v-loading指令
// directives/loading.js
export const vLoading = {