5
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 1 year has passed since last update.

<script setup>で動的コンポーネントを使う方法

Last updated at Posted at 2022-04-21

公式サイトみたいにやろうとしたら失敗した。

App.vue
<template>
  <label>
    <input type="radio" value="1" v-model="index">
    Sample1
  </label>
  <label>
    <input type="radio" value="2" v-model="index">
    Sample2
  </label>
  <label>
    <input type="radio" value="3" v-model="index">
    Sample3
  </label>
  <component :is="currentComponent"/>
</template>

<script setup>
import Sample1 from './Sample1.vue'
import Sample2 from './Sample2.vue'
import Sample3 from './Sample3.vue'

import { computed, ref } from 'vue'

const index = ref("1")
const currentComponent = computed(() => "sample" + index.value)
</script>

対処法を調べていると、以下の記事が見つかった。
https://stackoverflow.com/questions/69237991/vue-script-setup-how-to-deal-with-multiple-dynamic-components

どうやら<script setup>ではコンポーネントを名前で登録するのではなく、直接importしているため、上記のようにis属性に名前を渡してもどのコンポーネントか判断できないみたい。

以下のようにすると動いた。

App.vue
<template>
  <label>
    <input type="radio" value="1" v-model="index">
    Sample1
  </label>
  <label>
    <input type="radio" value="2" v-model="index">
    Sample2
  </label>
  <label>
    <input type="radio" value="3" v-model="index">
    Sample3
  </label>
  <component :is="SampleComponents[`sample${index}`]"/>
</template>

<script setup>
import Sample1 from './Sample1.vue'
import Sample2 from './Sample2.vue'
import Sample3 from './Sample3.vue'

import { computed, ref, shallowReactive } from 'vue'

const index = ref("1")
const SampleComponents = shallowReactive({
  sample1: Sample1,
  sample2: Sample2,
  sample3: Sample3
})
</script>

<script setup>だと自由度が高く柔軟な設計がしやすいので便利。

5
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
5
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?