六、Vue 高阶组件(HOC)与 Render 函数:解锁组件开发新姿势

1. 高阶组件(HOC)核心解析

1.1 HOC 本质与设计模式

高阶组件(Higher-Order Component)是一种基于组合模式的设计模式,通过函数接收组件并返回增强后的组件。其核心思想是逻辑复用,将通用功能抽象为可复用的 HOC,避免代码冗余。

1.2 HOC 基础实现

// 基础 HOC 结构
function hocFactory(WrappedComponent) {
   
   
  return {
   
   
    name: `HOC_${
     
     WrappedComponent.name}`,
    components: {
   
    WrappedComponent },
    props: {
   
   
      // 继承原组件 props
      ...WrappedComponent.props,
      // 添加新 props
      hocProp: {
   
    type: String, default: 'default' }
    },
    data() {
   
   
      return {
   
   
        hocData: 'HOC 内部数据'
      };
    },
    methods: {
   
   
      hocMethod() {
   
   
        console.log('HOC 方法被调用');
      }
    },
    render(h) {
   
   
      return h(WrappedComponent, {
   
   
        props: {
   
   
          ...this.$props,
          hocInjected: this.hocData
        },
        on: this.$listeners
      });
    }
  };
}

1.3 HOC 生命周期增强

// 生命周期增强 HOC
function withLifecycle(WrappedComponent) {
   
   
  return {
   
   
    mounted() {
   
   
      console.log('HOC mounted');
      this.$nextTick(() => {
   
   
        if (this.$refs.wrapped) {
   
   
          this.$refs.wrapped.init();
        }
      });
    },
    render(h) {
   
   
      return h(WrappedComponent, {
   
   
        ref: 'wrapped'
      });
    }
  };
}

// 使用示例
const EnhancedComponent = withLifecycle(OriginalComponent);

2. Render 函数深度实践

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值