Skip to content

Instantly share code, notes, and snippets.

@cades
Created April 21, 2017 05:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cades/9d9b33b245e4178cca6f90cf788e6ee5 to your computer and use it in GitHub Desktop.
Save cades/9d9b33b245e4178cca6f90cf788e6ee5 to your computer and use it in GitHub Desktop.
higher-order component for vue.js 2
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
);
},
};
};
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,
},
};
};
@joedski
Copy link

joedski commented Feb 14, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment