vue3 + antd4.x使用过程问题记录

本文介绍了在Vue3中如何使用shallowRef和markRaw处理动态组件,以避免性能开销,并展示了如何在组件切换时正确调用子组件的方法。
摘要由CSDN通过智能技术生成

1.vue3使用component动态组件,并使用ref来调用子组件的属性或方法

使用vue3动态组件的时候,需要使用shallowRef或者markRaw进行包裹组件,用于动态切换组件,不然会报错 App.vue:12 [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.

<template>
  <div>
  <button
       v-for="(item,index) in tabs"
       :key="index"
       @click="switch(item)"
     >
      {{ item.name}}
    </button>
    <!-- 使用component标签来渲染动态组件 -->
    <component :is="currentComponent" ref="dynamicComponent"></component>
    
    <button @click="callMethod">调用动态组件的方法</button>
  </div>
</template>
<script setup lang="ts">
import {
  reactive,
  ref,
  shallowRef,
  markRaw,
  nextTick
} from "vue";
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';

const tabs = [
  {
    name: "comp1",
    com: markRaw(ComponentA),
  },
  {
    name: "comp2",
    com: markRaw(ComponentB),
  },
];
let activeComp=ref(null)
let currentComponent= shallowRef(ComponentA );
const dynamicComponent= ref(null);

//调用方法
const callMethod =()=>{
	 if (activeComp.value== "comp2") {
      dynamicComponent.value.getData();
    }
}
//切换
const switch=(item)=>{
	currentComponent.value = item.comp;
	activeComp.value=item.name
	//切换后调用组件方法
	nextTick(() => {
    if (activeComp.value== "comp2") {
      dynamicComponent.value.getData();
    }
  });
}
</script>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值