【vue3】CompositionAPIで動的にrefを取得したい

投稿者:

こんな時

<template>
  <div v-for="i in [1,2,3]">
    <CompoA :ref="`component_a_${i}`"/>
  </div>
</template>

OptionsAPIではこんなふうにとれた

function callAMethod(i:string) {
  const a = this.$refs[`component_a_${i}`];
  a && a.publicMethod();
}

ドキュメントを見ると格納方法を関数で設定できるとのこと

https://ja.vuejs.org/guide/essentials/template-refs.html#function-refs

こんなふーにした

template

<template>
  <div v-for="i in [1,2,3]">
    <CompoA :ref="
      (el) => compoAList.set(`${i}`, el)
    "/>
  </div>
</template>

script

const compoAList = ref(new Map<string, InstanceType<typeof CompoA>>());

function callAMethod(i:string) {
  const a = compoAList.get(i);
  // CompoAの方でdefineExposeを忘れずに
  a && a.publicMethod();
}

Vue 3 フロントエンド開発の教科書