Skip to content

Instantly share code, notes, and snippets.

@heycqing
Last active October 10, 2023 02:17
Show Gist options
  • Select an option

  • Save heycqing/4fdc1ea4ceb3df98ec6a256a109cfa37 to your computer and use it in GitHub Desktop.

Select an option

Save heycqing/4fdc1ea4ceb3df98ec6a256a109cfa37 to your computer and use it in GitHub Desktop.
vue2的高阶函数
/**
* 里面的运作原理:
* 1. props的传递方式: props: WrappedComponent.props,
* 2. emit事件的传递方式: this.$emit(eventName, eventValue)
* 3. HOC内部的共用的逻辑处理,与简单操作原理
*
* @param {component} WrappedComponent
* @returns component
*/
export default function withSharedState(WrappedComponent) {
return {
name: `WithSharedState_${WrappedComponent.name}`,
props: WrappedComponent.props,
data() {
return {
sharedState: 1
};
},
methods: {
// HOC里面的特定操作
updateSharedState (newValue) {
this.sharedState = newValue;
},
// 传递到外部的方法
emitEvent (eventName, eventValue) {
this.$emit(eventName, eventValue)
}
},
render(h) {
// 使用 render 函数传递 sharedState 和 updateSharedState 到原始组件
return h(WrappedComponent, {
props: {
...this.$props,
sharedState: this.sharedState,
updateSharedState: this.updateSharedState,
// emit外部操作
emitEvent: this.emitEvent
},
});
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment