Is there a way to create Higher Order Components in Vue2?

37 Views Asked by At

I have a component that takes many props similar to:

ComponentA.vue

export default {
    props: {
        prop1: {
          type: Boolean,
          default: false
        },
        prop2: Boolean,
        ...
        prop7: Object
    }
}

Is there a way to create a higher order component that forwards all the props to ComponentA but sets some of them?

Essentially something equivalent to the following:

HigherComponentA.vue

<template>
   <ComponentA 
       :prop1="true"
       :prop2="prop2"
       ...
       :prop7="prop7"
   ></ComponentA>
</template>
<script>
export default {
    props: {
        prop2: Boolean,
        ...
        prop7: Object
    }
}
</script>

I have tried some variations of the following:

Vue.component("HigherComponentA", {
    render: (createElement) => {
        createElement(ComponentA, { props: { prop1: true } })
    },
    props: ComponentA.props
});

The issue is that while I'm able to set prop1 in createElement, I can't set the other props ahead of time and haven't found a way to make it just forward the props to ComponentA.

Is there a way to make this work in Vue?

For context, I often need variants of existing components and creating a new component file for every variant is not practical and also makes the files highly coupled.

Thanks in advance!

0

There are 0 best solutions below