LoginSignup
2
3

More than 1 year has passed since last update.

【Vue】コンポーネントの動的な切り替え

Posted at

実現すること

表示するコンポーネントをセレクトボックスで切り替える.
コンポーネントの動的切り替え.gif
データの入力方法をユーザに自由に選ばせたり,
一つのデータを色々な方法で見せるときに使えそう.

コンポーネントの用意

テキストボックス
BaseInput.vue
<template>
    <div class="dynamic-component">
        <input type="text" v-model="inputValue">
        <p>{{ inputValue }}</p>
    </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
const inputValue = ref("Hello Vue!");
</script>
ラジオボタン
BaseRadio.vue
<template>
    <div class="dynamic-component">
        <label>
            <input type="radio" name="memberType" value="1" v-model="memberType" />
            通常会員
        </label>
        <label>
            <input type="radio" name="memberType" value="2" v-model="memberType" />
            有料会員
        </label>
        <label>
            <input type="radio" name="memberType" value="3" v-model="memberType" />
            非会員
        </label>
        <br>
        <p>選択されたラジオボタン: {{ memberType }}</p>
    </div>
</template>


<script setup lang="ts">
import { ref } from "vue";

const memberType = ref(1);
</script>
セレクトボックス
BaseSelect.vue
<template>
    <div class="dynamic-component">
        <select v-model="memberType">
            <option value="1">通常会員</option>
            <option value="2">有料会員</option>
            <option value="3">非会員</option>
        </select>
        <br>
        <p>選択されたリスト: {{ memberType }}</p>
    </div>
</template>


<script setup lang="ts">
import { ref } from "vue";

const memberType = ref(1);
</script>

アプリケーション

  • <component :is="currentComp" />
    • 動的コンポーネントを読み込むためのタグ
    • v-bind:isで表示するコンポーネントを指定する
  • <keep-alive>
    • コンポーネントを動的に切り替えた時に状態を保持する
    • 切り替えるたびに初期状態にしたい場合は不要
App.vue
<template>
  <h1>動的コンポーネント</h1>
  <select v-on:change="switchComp">コンポーネントを切り替える
    <option value="0">Input</option>
    <option value="1">Radio</option>
    <option value="2">Select</option>
  </select>
  <p>コンポーネント名: {{ currentCompName }}</p>
  
  <keep-alive>
    <component :is="currentComp" />
  </keep-alive>
</template>

<script setup lang="ts">
import { ref } from "vue";
import BaseInput from "./components/BaseInput.vue";
import BaseRadio from "./components/BaseRadio.vue";
import BaseSelect from "./components/BaseSelect.vue";

const currentComp = ref(BaseInput);
const currentCompName = ref("Input");
const compList = [BaseInput, BaseRadio, BaseSelect];
const compNameList: string[] = ["Input", "Radio", "Select"];

let compIdx = 0;
const switchComp = () => {
  compIdx = ++compIdx % compList.length;
  currentComp.value = compList[compIdx];
  currentCompName.value = compNameList[compIdx];

}
</script>

<style scoped>
.dynamic-component {
  border: green 1px solid;
}
</style>
2
3
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
3