Vue3:动态组件

使用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>

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值