(vue3)动态组件

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

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

<template>
    <div style="display: flex;">
       <div @click="switchCom(item,index)" 
            :class="[active == index ? 'active':'']" 
            class="tabs" v-for="(item,index) in data" :key="index">
          <div>{
   
   { item.name }}</div>
       </div>
    </div>
    <!-- 内置组件 -->
    <component :is="comId"></component>
</template>
<script setup lang='ts'>
import { ref, reactive, shallowRef, markRaw } from 'vue'
import AP from '@/components/expame/AP.vue'
import BP from '@/components/expame/BP.vue'
import CP from '@/components/expame/CP.vue'

const comId = shallowRef(AP) // 切换组件
const active = ref(0)  // 点击tab动态样式
const data = reactive([  
   {
      name:'A组件',
      com:markRaw(AP)
   },
   {
      name:'B组件',
      com:markRaw(BP)
   },
   {
      name:'C组件',
      com:markRaw(CP)
   }
])
// 点击事件
const switchCom = (item , index) => {
   comId.value = item.com
   active.value = index
}
</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 包裹组件

猜你喜欢

转载自blog.csdn.net/weixin_45959965/article/details/130039600