• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue3动态组件

武飞扬头像
吃不饱的小明同学
帮助1

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

在挂载点使用component标签,然后使用v-bind:is=”组件 ,通过is 切换 A B 组件

  1.  
    <template>
  2.  
    <div style="display: flex;">
  3.  
    <div @click="switchCom(item,index)"
  4.  
    :class="[active == index ? 'active':'']"
  5.  
    class="tabs" v-for="(item,index) in data" :key="index">
  6.  
    <div>{{ item.name }}</div>
  7.  
    </div>
  8.  
    </div>
  9.  
    <!-- 内置组件 -->
  10.  
    <component :is="comId"></component>
  11.  
    </template>
  1.  
    <script setup lang='ts'>
  2.  
    import { ref, reactive, shallowRef, markRaw } from 'vue'
  3.  
    import AP from '@/components/expame/AP.vue'
  4.  
    import BP from '@/components/expame/BP.vue'
  5.  
    import CP from '@/components/expame/CP.vue'
  6.  
     
  7.  
    const comId = shallowRef(AP) // 切换组件
  8.  
    const active = ref(0) // 点击tab动态样式
  9.  
    const data = reactive([
  10.  
    {
  11.  
    name:'A组件',
  12.  
    com:markRaw(AP)
  13.  
    },
  14.  
    {
  15.  
    name:'B组件',
  16.  
    com:markRaw(BP)
  17.  
    },
  18.  
    {
  19.  
    name:'C组件',
  20.  
    com:markRaw(CP)
  21.  
    }
  22.  
    ])
  23.  
    // 点击事件
  24.  
    const switchCom = (item , index) => {
  25.  
    comId.value = item.com
  26.  
    active.value = index
  27.  
    }
  28.  
    </script>
学新通

使用场景

tab切换 居多

注意事项 

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

2.如果你把组件实例放到Reactive Vue会给你一个警告runtime-core.esm-bundler.js:38 [Vue warn]: Vue received a 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`. 
Component that was made reactive: 

这是因为reactive 会进行proxy 代理 而我们组件代理之后毫无用处 节省性能开销 推荐我们使用shallowRef 或者  shallowRef 跳过proxy 代理
所以上面要使用shallowRef , shallowRef 包裹组件

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbehfc
系列文章
更多 icon
同类精品
更多 icon
继续加载