2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vue.js Composition API】v-forの中で子コンポーネントの参照を使用する with TypeScript

Posted at

Vue.js の Composition API でref属性を使用した子コンポーネントの参照をv-for内で使用する場合の備忘録です。
今回は TypeScript も使用しています。

<template>
  <div>
    <HelloWorld
      v-for="(item, i) in list"
      :key="item"
      :ref="el => { if (el) helloWorldComponents[i] = el }"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onBeforeUpdate } from 'vue';
import HelloWorld from './components/HelloWorld.vue';

export default defineComponent({
  components: {
    HelloWorld,
  },
  setup() {
    const list = reactive([1, 2, 3]);

    const helloWorldComponents = ref<InstanceType<typeof HelloWorld>[]>([]);

    onBeforeUpdate(() => {
      // Updateの前に必ず参照をリセットする
      helloWorldComponents.value = [];
    });

    return { list, helloWorldComponents };
  },
});
</script>

参考文献

Usage inside v-for
Vue.js の Composition API における this.$refs の取得方法

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?