Vue 的 <component :is> 让你在运行时动态决定要渲染的组件,而 <KeepAlive> 会缓存这些组件,使它们在切换离开和返回时保持状态。
使用 <component :is> 的动态组件
vue
<script setup>
import { ref, shallowRef } from "vue";
import TabHome from "./TabHome.vue";
import TabProfile from "./TabProfile.vue";
const tabs = { home: TabHome, profile: TabProfile };
const current = shallowRef(TabHome); // which component to show
</script>
<template>
<button @click="current = tabs.home">Home</button>
<button @click="current = tabs.profile">Profile</button>
<component :is="current" /> <!-- renders whichever component `current` holds -->
</template>
