javascripttypescriptvue.jsrecursionvueuse

How to correctly type useTemplateRefsList in a recursive component in Vue 3?


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

  1. Using ComponentPublicInstance:
const refs = useTemplateRefsList<ComponentPublicInstance>();

But this type is too generic and doesn’t reflect the actual instance of the recursive component.

  1. Using InstanceType:
const refs = useTemplateRefsList<InstanceType<typeof RecursiveComponent>>();

However, RecursiveComponent isn’t defined yet during its own declaration, which creates a circular dependency issue.

  1. 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.

  1. 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!


Solution

  • With Vue 3.5+ you can use useTemplateRef which is typed automatically, inferred.

    There's though a HACK. To make useTemplateRef to infer the recursive child component, import it with a different name, otherwise the internal instance would be inferred, not the exposed one:

    Playground

    <script lang="ts" setup>
    import CompChild from './Comp.vue';
    type Item = {name: string, children?: Item[]};
    defineProps<{
      data: Item
    }>();
    
    import {ref} from 'vue';
    import { useTemplateRef } from 'vue';
    const $comps = useTemplateRef('$comps');
    
    defineExpose({
      addColor(){
        color.value = 
          ['red', 'green', 'lime', 'blue', 'orange', 'skyblue'][Math.random()* 6 | 0];
        $comps.value?.forEach($comp => $comp.addColor());
      }
    });
    
    const color = ref('inherit');
    
    </script>
    
    <template>
      <div style="padding-left: 24px">
        <div>{{ data.name }}</div>
        <CompChild ref="$comps" v-if="data.children" v-for="item in data.children" :data="item"/>
      </div>
    </template>
    
    <style scoped>
    div{
      background-color: v-bind(color);
    }
    </style>