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

在挂载点使用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>

效果

 

Logo

前往低代码交流专区

更多推荐