create vue 3 wrapper component in typescript

To create a Vue 3 wrapper component in TypeScript, follow these steps:

  1. Create a new TypeScript file with desired name for your wrapper component, for example MyWrapperComponent.ts. Make sure to include the .ts extension.
  2. Create a new Vue 3 component object using the Vue defineComponent function.
  3. Define the name property for the component object to give your wrapper component a name.
  4. Define the props property as an object with all the props that will be passed to the wrapped component. You'll need to add the ...attrs spread operator to pass any extra attributes to the wrapped component.
  5. Define the render function which returns a h function that creates and returns a new instance of the wrapped component. Pass in the props and attrs objects to the wrapped component instance.
  6. Export the new Vue 3 component object.

Here's how the final code for your wrapper component might look like:

index.ts
import { defineComponent, h } from 'vue'
import WrappedComponent from './WrappedComponent.vue'

export default defineComponent({
  name: 'MyWrapperComponent',
  props: {
    propA: {
      type: String,
      required: true
    },
    propB: {
      type: Number,
      default: 42
    }
  },
  render() {
    return h(WrappedComponent, {
      ...this.props,
      ...this.attrs
    })
  }
})
394 chars
23 lines

In this example, the MyWrapperComponent component is defined with two props: propA and propB. The render function creates a new instance of the WrappedComponent component and passes in all the MyWrapperComponent's props and attrs.

Make sure to change the ./WrappedComponent.vue import statement to the path of your own wrapped component.

gistlibby LogSnag