vue3笔记五(:is 动态组件)

1、注意事项

1、在Vue2 的时候is是通过组件名称切换的,在Vue3 setup是通过组件实例切换的

2、如果直接把组件实例放到reactive中代理,vue会发出警告。告知我们可以通过shallowRef 或者 markRaw 跳过proxy 代理。
因为组件实例进行响应式代理毫无意义,且浪费性能
在这里插入图片描述

2、:is 动态组件使用

子组件通过defineProps接受传参

<template>
  <div class="content">
    <div class="tabs" v-for="item in tabArr" :key="item.name" @click="tabChange(item.comName)">
      {{ item.name }}
    </div>
  </div>
  <component :is="currentCom"></component>
</template>

<script setup lang="ts">
  import { ref, reactive, markRaw } from 'vue'
  import A from './A.vue'
  import B from './B.vue'
  import C from './C.vue'

  type Tab = {
    name: string,
    comName: any
  }

  // 从复杂数据类型中取出自己想要的几个属性
  type Com = Pick<Tab, 'comName'>

  const tabArr = reactive<Tab[]>([
    {
      name: 'A组件',
      comName: markRaw(A)
    },
    {
      name: 'B组件',
      comName: markRaw(B)
    },
    {
      name: 'C组件',
      comName: markRaw(C)
    },
  ])

  const currentCom = ref<Com>(tabArr[0].comName)

  const tabChange = (item: Com) => {
    currentCom.value = item
  }
</script>

<style>
  .content {
    display: flex;
    padding: 20px;
    height: 40px;
    width: 100vw;
    background: #f1f1f1;
  }
  .tabs {
    width: 100px;
    height: 40px;
    background: #ffffff;
    margin-right: 5px;
    border: 1px solid #000;
  }
</style>

原文链接:https://xiaoman.blog.csdn.net/article/details/122891279

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值