DEV Community

Cover image for How to use generic component in vue3 and typescript?
ltmonster
ltmonster

Posted on

How to use generic component in vue3 and typescript?

When we created a generic component with vue3 and typescript,how should we utilize it?
This is a simple generic component and expose a getName function.

<template>
    <div>
        My name is {{ name }}.
    </div>
</template>

<script lang="ts" setup generic="T extends String">

const props = defineProps<{
    name: T
}>()

function getName(){
    return props.name
}

defineExpose({
    getName
})

</script>
Enter fullscreen mode Exit fullscreen mode

We need to install a javascript library called vue-component-type-helpers.

pnpm add vue-component-type-helpers
Enter fullscreen mode Exit fullscreen mode

Use this in <script>

<template>
    <div>
        <MyComponent ref="myComponentRef" name="John" />
    </div>
</template>

<script lang="ts" setup>
import MyComponent from '@/components/MyComponent.vue'
import type { ComponentExposed } from 'vue-component-type-helpers'

//👍vue3.5+
const introduceRef = useTemplateRef<ComponentExposed<typeof MyComponent>>('myComponentRef')

//other version
const introduceRef2 = ref<ComponentExposed<typeof MyComponent>>()
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)