父页面:index.vue
<template>
<div>
<component :is="A" />
</div>
</template>
<script setup lang='ts'>
import A from '../components/A.vue'
</script>
子组件:A.vue
<template>
<div>
A组件内容
</div>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
</script>
我们实现一个选项卡:
父页面:index.vue
<template>
<div>
<div v-for="(item,index) in data" :key="item.comName">
<button @click="switchCom(item)">{{item.name}}</button>
</div>
<component :is="current.comName"></component>
</div>
</template>
<script setup lang='ts'>
import { reactive, ref, markRaw } from 'vue'
import A from '../components/A.vue'
import B from '../components/B.vue'
type Tabs = {
name: string,
comName: any
}
type Com = Pick<Tabs, 'comName'>
const data = reactive<Tabs[]>([
{
name: "com-A",
comName: markRaw(A)
}, {
name: "com-B",
comName: markRaw(B)
}
])
let current = reactive<Com>({
comName: data[0].comName
})
const switchCom = (item:Tabs) => {
current.comName = item.comName
}
</script>
子组件:A.vue
<template>
<div>
AAA
</div>
</template>
子组件:B.vue
<template>
<div>
BBB
</div>
</template>