I’m working on a recursive Vue 3 component using the Composition API and the useTemplateRefsList
function from @vueuse/core
.
My goal is to collect references to each instance of the recursive component. However, I’m struggling to type the list of references correctly, as the this
keyword is not available in the Composition API.
Here’s a simplified version of my setup:
// toto.vue
<template>
{{ data.name }}
<toto
v-for="item in data.children"
ref="childRefs"
:key="item.id"
:data="item.children"
/>
</template>
<script setup lang="ts">
import { useTemplateRefsList } from '@vueuse/core';
const { data } = defineProps<{
id: string;
name: string;
children?: [
{
id: string;
name: string,
children?: [...]
}
]
}>();
// Attempting to type the refs list
const childRefs = useTemplateRefsList</* What type goes here? */>();
</script>
Problem
I want to type childRefs
such that it correctly represents an array of the recursive component’s instances.
Since this
is unavailable in the script setup syntax, I cannot directly refer to the component’s instance type.
What I’ve tried
- Using
ComponentPublicInstance
:
const refs = useTemplateRefsList<ComponentPublicInstance>();
But this type is too generic and doesn’t reflect the actual instance of the recursive component.
- Using
InstanceType
:
const refs = useTemplateRefsList<InstanceType<typeof RecursiveComponent>>();
However, RecursiveComponent isn’t defined yet during its own declaration, which creates a circular dependency issue.
- Typing via
expose
I considered using defineExpose to expose properties/methods and type against those, but this feels like overkill for a simple recursive component.
- Export type from another
ts file
// definitionsFile.ts
import Toto from './Toto.vue';
// Without using an object, I get the following error: Type alias 'TotoType' circularly references itself.
export type TotoType = { a: InstanceType<typeof PermissionSummaryRow> };
// toto.vue
import Toto from './Toto.vue';
// 'childRefs' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer
const childRefs = useTemplateRefsList<TotoType['a']>();
// any
const test = childRefs.value[0]!;
Question
What is the correct way to type useTemplateRefsList
for a recursive component in Vue 3? Is there a way to dynamically reference the current component’s type, or is there a workaround to achieve this?
Any help or guidance would be appreciated!