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);

最低0.47元/天 解锁文章
215

被折叠的 条评论
为什么被折叠?



