[Vuejs]-How to type vue Component in props

0👍

You can start by creating a component and rendering it using Vue’s h function:

import { defineComponent } from 'vue'
const FieldRender = defineComponent({
  name: 'FieldRender',
  props: {
    value: {
      type: [String, Number, Object] as PropType<string | number | VNode | Component>,
      default: '',
    },
  },
  setup(props) {
    return () => {
      if (typeof props.value === 'string' || typeof props.value === 'number')
        return props.value
      return props.value ? h(props.value) : null
    }
  },
})

To use it, you can do the following:

<template>
  <FieldRender :value="text" />
</template>

<script setup>
import { Component, VNode } from 'vue'
const props = defineProps<{
  text?: Component | number | string
}>()
</script>

This code is implemented in @unoverlays/vue, so you can also install @unoverlays/vue and use it directly:

pnpm i @unoverlays/vue
<template>
  <FieldRender :value="text" />
</template>

<script setup>
import { FieldRender } from '@unoverlays/vue'
import { Component, VNode } from 'vue'
const props = defineProps<{
  text?: string | number | VNode | Component
}>()
</script>

If you want to validate props, you can use the validator of props.

Leave a comment