> 文章列表 > Vue 3 第十二章:组件三(动态组件-component)

Vue 3 第十二章:组件三(动态组件-component)

Vue 3 第十二章:组件三(动态组件-component)

文章目录

  • 1. 动态组件
    • 1.1. 动态组件的概念
    • 1.2. 动态组件的使用和实现
  • 总结

1. 动态组件

1.1. 动态组件的概念

多个组件通过component标签挂载在同一个组件中,通过触发动作进行动态切换。常搭配<keep-alive></keep-alive>使用,多用于tab栏的切换等场景

1.2. 动态组件的使用和实现

在Vue中,我们可以通过设置<component>标签的is属性来指定要渲染的组件。

例如,我们可以通过以下方式来动态切换不同的组件:

  • Component.vue
// Component.vue
<template><div><buttonv-for="(item, index) in tabs":key="index"@click="currentTab = item.comName">{{ item.name }}</button><component :is="currentTab" class="tab"></component></div>
</template><script setup lang="ts">
import ComA from './components/ComA.vue'
import ComB from './components/ComB.vue'
import { reactive, shallowRef } from 'vue'// reactive 会使数据变成响应式,此处为了节省性能开销,可以使用 shallowRef 或者 markRaw 跳过 proxy 代理
const currentTab = shallowRef(ComA)
const tabs = reactive([{name: 'ComA',comName: shallowRef(ComA)},{name: 'ComB',comName: shallowRef(ComB)},
])
</script><style scoped>
</style>

总结

在 Vue 中,使用<component :is=>标签可以动态渲染不同的组件,可以根据变量的值来动态切换不同的子组件。
vue 2 is接收的是组件名称,vue 3 is接收的是组件实例。为了节省性能开销,我们还可以使用shallowRef或者markRaw跳过proxy代理。