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>
We need to install a javascript library called vue-component-type-helpers
.
pnpm add vue-component-type-helpers
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>
Top comments (0)