41
Vue 3 學習之旅
高級特性

Day 41: 動態元件:<component :is="...">

·6 分鐘閱讀·動態元件

摘要

動態元件 <component> 是一個特殊的「元元件」,它允許我們在同一個掛載點,根據一個變數的值,動態地切換要渲染的元件。

定義與說明

<component> 元素透過其特殊的 is 屬性來決定要渲染哪一個元件。is 屬性的值可以是一個已註冊元件的名稱字串,或是一個元件的選項物件。當 is 屬性綁定的變數改變時,元件就會被切換,舊元件會被銷毀,新元件會被建立。

實作範例

動態元件示例
<script setup>
import { ref, shallowRef } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';

const tabs = { ComponentA, ComponentB };
const currentTab = shallowRef(ComponentA);
</script>

<template>
  <button @click="currentTab = tabs.ComponentA">顯示 A</button>
  <button @click="currentTab = tabs.ComponentB">顯示 B</button>

  <!-- :is 屬性綁定了 currentTab 變數,動態切換元件 -->
  <component :is="currentTab" />
</template>

結論

動態元件是實現頁籤 (Tabs)、多步驟表單等需要動態切換視圖場景的理想工具。它提供了一種靈活、宣告式的方式來管理元件的動態渲染。

動態元件 component 切換