首页 前端知识 vue3学习(九)动态组件 实现 tab切换

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

2024-06-03 12:06:43 前端知识 前端哥 600 722 我要收藏

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

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

效果

 

转载请注明出处或者链接地址:https://www.qianduange.cn//article/10631.html
标签
评论
还可以输入200
共0条数据,当前/页
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!