(vue3) dynamic components

What is a dynamic component is: let multiple components use the same mount point and switch dynamically, this is a dynamic component.

Use the component tag at the mount point , then use v-bind :is="component, switch the AB component through is

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

scenes to be used

tab switching  mostly

Precautions 

1. In Vue2, is is switched by component name, in Vue3 setup is switched by component instance

2. If you put the component instance into Reactive Vue will give you a warning 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: 

This is because reactive will perform proxy proxy and our component proxy is useless to save performance overhead. It is recommended that we use shallowRef or shallowRef to skip proxy proxy,
so shallowRef should be used above, and shallowRef wraps components

Guess you like

Origin blog.csdn.net/weixin_45959965/article/details/130039600
Recommended