<template>
	<div class="home_main">
		<Tree :list="navBarList" />
		<ul class="tab_list">
			<li @click="changeComponent(item)" v-for="(item, index) in componentArr" :key="index">
				{{ item.name }}
			</li>
		</ul>
		<component :is="current.comName"></component>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref, markRaw } from "vue";
import A from '@/components/childComponent/A.vue'
import B from '@/components/childComponent/B.vue'
import C from '@/components/childComponent/D.vue'
//建议我们使用组件跳过代理  markRaw  使用的时候我们会打印出__v_skip:true;节省性能
type Tabs = {
	name: string,
	comName: any
}
const componentArr = reactive<Tabs[]>([
	{
		name: '我是组件A',
		comName: markRaw(A)
	},
	{
		name: '我是组件B',
		comName: markRaw(B)
	},
	{
		name: '我是组件C',
		comName: markRaw(C)
	}
])
type Com = Pick<Tabs, 'comName'>
let current = reactive<Com>({
	comName: componentArr[0].comName
})
const navBarList = reactive([
	{
		name: '一级导航 1'
	},
	{
		name: '一级导航 2',
		children: [
			{ name: '二级导航 2-1' },
			{
				name: '二级导航 2-2',
				children: [
					{ name: '三级导航 2-2-1' },
					{ name: '三级导航 2-2-2' },
				]
			},
			{ name: '二级导航 2-2' }
		]
	},
	{
		name: '一级导航 3'
	}
])
const changeComponent = (item: Tabs) => {
	current.comName = item.comName
}
</script>

<style lang="scss">
.home_main {
	width: 100%;
	height: 100%;
	background: #d7d7d7;
	font-size: 30px;
	color: aqua;

	.tab_list {
		display: flex;
		justify-content: space-between;
		width: 700px;

		li {
			border: 1px solid #333;
			font-size: 18px;
			color: #fff
		}
	}
}
</style>

注意vue3中在compositionApi形式中不可以用字符串形式,如下形式是错误的

const componentArr = reactive<Tabs[]>([
	{
		name: '我是组件A',
		comName: 'A'
	},
	{
		name: '我是组件B',
		comName: 'B'
	},
	{
		name: '我是组件C',
		comName: 'C'
	}
])

如下这个字符串形式也是不行的只可以通过动态传参,除非用optionApi形式可以的

<component :is="Ak"></component>
<script>
import A from '@/components/childComponent/A.vue'
</script>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐