使用component内置组件,通过is绑定要展示的组件
多用于tab页切换的场景
markRaw的作用及应用(必须使用markRaw跳过对组件的代理,否则vue会给警告)
效果图
?Vue2回顾
<template>
<div>
<component :is="A"></component>
</div>
</template>
<script>
import A from './A';
export default {
name: 'paysuccess',
data() {
return {
}
},
components: {
A
},
}
</script>
<style lang="less" scoped>
</style>
Vue3:
<template>
<div class="tabs-content" @click="switchTab(tab)" v-for="(tab, index) in tabData" :key="index">
{{ tab.name }}
</div>
<component :is="currentTab.tabComp"></component>
</template>
<script setup lang="ts">
import { reactive, markRaw } from 'vue'
import A from './A.vue'
import B from './B.vue'
import C from './C.vue'
type tabType = {
name: string,
tabComp: any
}
type Comp = Pick<tabType, 'tabComp'>
const tabData = reactive<tabType[]>([
{
name: 'A组件',
// proxy会代理reactive中的所有内容
// 无需对组件进行proxy代理
// 必须使用markRaw跳过对组件的代理,否则vue会给警告
tabComp: markRaw(A)
},
{
name: 'B组件',
tabComp: markRaw(B)
},
{
name: 'C组件',
tabComp: markRaw(C)
},
])
let currentTab = reactive<Comp>({
tabComp: tabData[0].tabComp
})
const switchTab = (tab: tabType) => {
currentTab.tabComp = tab.tabComp
}
</script>
<style scoped lang="less">
.tabs-content {
display: inline-block;
width: 100px;
border: 1px solid #ccc;
background: rgb(175, 96, 96);
color: white;
}
</style>
|