Skip to content

Vue 动态组件

Vue 动态组件

简介

有些场景会需要在两个组件间来回切换,比如 Tab 界面。

此时可以通过 Vue 的 <component> 元素和特殊的 is 属性实现不同组件的切换显示。

<component :is="..."></component>

传给 :is 属性的值可以是导入的组件对象。

示例代码

SoltIsHomeSC.vue

<template>
    <div>
      HOME 组件
    </div>
  </template>

SoltIsAboutSC.vue

<template>
    <div>
      About 组件
    </div>
  </template>

SoltIsFC.vue

<script setup>
import Home from './SlotIsHomeSC.vue'
import About from './SlotIsAboutSC.vue'
import { ref } from 'vue'

const currentTab = ref('Home')

const tabs = {
  Home,
  About
}

</script>

<template>
  <div class="demo">
    <button
       v-for="(_, tab) in tabs"
       :key="tab"
       :class=" { active: currentTab === tab }"
       @click="currentTab = tab"
     >
      {{ tab }}
    </button>
      <component :is="tabs[currentTab]" ></component>
  </div>
</template>

<style>
    .active {
    background: red;
    }
</style>

App.vue

<script setup>
    import SlotIsFC from "./components/MyComponents/SlotIsFC.vue";
</script>

<template>
    <SlotIsFC></SlotIsFC>
</template>

当使用 <component :is="..."> 来在多个组件间作切换时,被切换掉的组件会被卸载。

我们可以通过 <KeepAlive> 组件强制被切换掉的组件仍然保持“存活”的状态。

总结

  • 在需要同一个位置展示不同的组件时,可以使用动态组件实现。
  • 动态组件使用 <component :is="..."> 在父组件中渲染子组件