Created
April 21, 2017 05:51
-
-
Save cades/9d9b33b245e4178cca6f90cf788e6ee5 to your computer and use it in GitHub Desktop.
higher-order component for vue.js 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function(WrappedComponent) { | |
const mixinProps = (WrappedComponent.mixins || []) | |
.filter((mixin) => mixin.props) | |
.map((mixin) => mixin.props); | |
const allProps = mixinProps.concat(WrappedComponent.props); | |
const mergedProps = allProps.reduce((merged, props) => Object.assign(merged, props), {}); | |
return { | |
props: mergedProps, | |
render(createElement) { | |
return createElement( | |
WrappedComponent, | |
{ props: this.$props }, | |
this.$slots.default | |
); | |
}, | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function(WrappedComponent) { | |
const mixinProps = (WrappedComponent.mixins || []) | |
.filter((mixin) => mixin.props) | |
.map((mixin) => mixin.props); | |
const allProps = mixinProps.concat(WrappedComponent.props); | |
const mergedProps = allProps.reduce((merged, props) => Object.assign(merged, props), {}); | |
const propsInterpolation = Object.keys(mergedProps) | |
.map((key) => `:${key}="${key}"`) | |
.join(' '); | |
return { | |
template: `<wrapped ${propsInterpolation}><slot></slot></wrapped>`, | |
props: mergedProps, | |
components: { | |
'wrapped': WrappedComponent, | |
}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Studying https://gist.github.com/cades/9d9b33b245e4178cca6f90cf788e6ee5#file-hoc-after-2-2-0-js I was initially confused as to why you needed to copy the props like that. I realized however that, since this is a HOC and not a mixin, and therefore composes rather than merges, the HOC doesn't get all of those props itself automatically, hence why you had to copy them all in order to present the proper interface.