vue3学习(九)动态组件 实现 tab切换

让多个组件使用同一个挂载点,并动态切换,这就是动态组件。

在挂载点使用component标签    <component :is="comId"></component>

引入组件

import AVue from './components/abComponrnts/A.vue'
import BVue from './components/abComponrnts/B.vue'

组件实例信息 

如果你把组件实例放到Reactive Vue会给你一个警告:Component which was made a reactive object. This can lead to unnecessary performance overhead, and should be avoided by marking the component with `markRaw` or using `shallowRef` instead of `ref`. 

Vue 收到一个组件,它被做成一个反应性对象。这可能会导致不必要的性能开销,应通过使用“markRaw”标记组件或使用“shallowRef”而不是“ref”来避免。

const comId = shallowRef(AVue)
const dataCom = reactive([
    {
        name:'A组件',
        com:markRaw(AVue)
    },{
        name:'B组件',
        com:markRaw(BVue)
    }
])

 遍历dataCom

设置动态样式active

设置点击切换事件

    <div class="tabs">
        <div  
        @click="switchCom(item,index)"
        :class="[bColor == index? 'active' : '']" 
        class="tabs-card" 
        v-for="(item,index) in dataCom">
            <div> {{ item.name }}</div>
        </div>
    </div>
    <component :is="comId"></component>

完整ts代码

<script setup lang='ts'>
import {ref,reactive,markRaw,shallowRef} from 'vue'
import AVue from './components/abComponrnts/A.vue'
import BVue from './components/abComponrnts/B.vue'

// 动态组件,导航切换
const comId = shallowRef(AVue)
const bColor = ref(0)
const dataCom = reactive([
    {
        name:'A组件',
        com:markRaw(AVue)
    },{
        name:'B组件',
        com:markRaw(BVue)
    }
])
const switchCom = (item:any,index:number)=>{
    comId.value = item.com
    bColor.value = index
}
</script>
<style scoped lang="less">
.active{
    background-color: aqua;
}
.tabs{
    display: flex;
    &-card{
        border: 1px solid #ccc;
        padding: 5px 10px;
        margin: 10px;
        cursor: pointer;
    }
}
</style>

效果

 

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值