700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > vue3学习(九)动态组件 实现 tab切换

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

时间:2022-05-19 05:47:32

相关推荐

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 = 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>

效果

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。