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

Quickstart image

Django MongoDB Backend Quickstart! A Step-by-Step Tutorial

Get up and running with the new Django MongoDB Backend Python library! This tutorial covers creating a Django application, connecting it to MongoDB Atlas, performing CRUD operations, and configuring the Django admin for MongoDB.

Watch full video →

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

đź‘‹ Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay