1. 动态组件
1.1. 动态组件的概念
多个组件通过
component
标签挂载在同一个组件中,通过触发动作进行动态切换。常搭配<keep-alive></keep-alive>
使用,多用于tab栏的切换等场景
1.2. 动态组件的使用和实现
在Vue中,我们可以通过设置<component>
标签的is
属性来指定要渲染的组件。
例如,我们可以通过以下方式来动态切换不同的组件:
- Component.vue
// Component.vue
<template>
<div>
<button
v-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
代理。