方案1:定义为响应式数组;根据索引 index 访问组件
浅响应 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>