vue3使用is动态切换组件报错Vue received a Component which was made a reactive object.

225 篇文章 1 订阅
199 篇文章 4 订阅

vue3使用is动态切换组件,activeComponent用ref定义报错
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

在这里插入图片描述

我们需要使用 shallowRef 替代 ref 来避免报错。shallowRef 创建的引用不会将组件标记为响应式对象,从而避免了潜在的性能开销。

<button @click="switchComponent('componentA')">Component A</button>
<button @click="switchComponent('componentB')">Component B</button>
<component :is="currentComponent"></component>
 
 
<script setup name="swtichComponent">
import { computed, ref, markRaw } from 'vue'
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
 
 
const currentComponent = ref(markRaw(ComponentA));
 
function switchComponent(component) {
  if (component === 'componentA') {
    currentComponent.value = markRaw(ComponentA);
  } else if (component === 'componentB') {
    currentComponent.value = markRaw(ComponentB);
  }
}
 
</script>

父子组件通信

父:
<component :is="activeComponent" @handleChange="handleChange" />
 
function handleClose() {
  window.close()
}
 
子:
const emits = defineEmits(['handleChange'])
const handleChange= () => {
  emits('handleChange')
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值