DEV Community

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

Posted on

1 1 1 1 1

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more