动态组件

@Dynamic
Introduction
Dynamic Components:使用特殊元素 <component> 和配合 :is 属性实现多组件选一/两个或多个组件间来回切换 - dynamically switch between components
被切换掉的组件会被卸载。通过 <KeepAlive> 组件强制被切换掉的组件仍然保持“存活”的状态
应用:标签页、导航页
<component v-else :is=""></component>
<component>
特殊元素
一个用于渲染动态组件或元素的“元组件”
要渲染的实际组件由属性 is 决定
:is
is:要渲染的组件
. HTML 标签名、注册/导入的组件名
. 直接绑定到组件的定义
Drill
[] 基本使用 - 使用注册的组件名
根据条件判断并切换组件
import Work from './components/Work.vue';
import Team from './components/Team.vue';
<component v-if="flag" :is="Work"></component>
<component v-else :is="Team"></component>
使用三元表达式优化代码
<component v-else :is="flag ? Work : Team"></component>
[] 标签页组件 Tabcard.vue - 动态组件静态数据版
创建组件:除了基本信息外,为每个组件指定2个生命周期函数/钩子
onMounted(() => {
  console.log('TabGoods onMounted');
})
onUnmounted(() => {
  console.log('TabGoods unmounted');
})
逻辑:导入组件;定义为静态数组
import TabGoods from './components/TabGoods.vue';
import TabCup from './components/TabCup.vue';
const index = ref(0)
const tabs = [{
  id: 0,
  label: '随享瑞幸',
  component: TabGoods
}, {
  id: 1,
  label: '颜值水杯',
  component: TabCup
}]
结构:列表渲染;根据索引 index 访问组件
<span v-for="(tab, ind) in tabs" @click="index = ind">{{ tab.label }}</span>
<component :is="tabs[index].component"></component>
查看组件切换时,控制台的输出
分析上述2个案例的特点
Summary & Homework
Summary
<component>
is
Homework
[] 标签页组件 Tabcard.vue - 动态组件版其它方案
方案1:定义为响应式数组;根据索引 index 访问组件
ref 默认是深层响应;为了避免性能上的消耗,使用 浅响应 shallowRef
浅响应 shallowRef 创建一个浅响应式对象,数据的深层改变不会触发视图更新,减少性能上的消耗;并不对其中的数据进行响应,仅仅对对象的名字响应
import { ref, shallowRef } from 'vue'
import TabGoods from '@/components/TabGoods.vue'
import TabCup from '@/components/TabCup.vue'

const index = ref(0)
const tabs = shallowRef([{
  id: 0,
  label: '随享瑞幸',
  component: TabGoods
}, {
}, {
  id: 1,
  label: '颜值水杯',
  component: TabCup
}])
<span v-for="(tab, ind) in tabs" @click="index = ind">{{ tab.label }}</span>
<component :is="tabs[index].component"></component>
方案2:定义为静态对象;遍历对象,根据 key 访问组件;相对简洁
import TabGoods from '@/components/TabGoods.vue'
import TabCup from '@/components/TabCup.vue'

const currentTab = ref('随享瑞幸')
const tabs = {
  "随享瑞幸": TabGoods,
  "颜值水杯": TabCup
}
<span v-for="(value, key) in tabs" @click="currentTab = key">{{ key }}</span>
<component :is="tabs[currentTab]"></component>
不用 value;也可以使用_表示省略;非标准语法
<span v-for="(_, key) in tabs" @click="currentTab = key">{{ key }}</span>
<component :is="tabs[currentTab]"></component>