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

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 创建的引用不会将组件标记为响应式对象,从而避免了潜在的性能开销。

javascript 复制代码
<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>

切换组件不能做全局相关操作,例如关闭当前页面,需要子传父调用

javascript 复制代码
父:
<component :is="activeComponent" @close="handleClose" />

function handleClose() {
  window.close()
}

子:
const emits = defineEmits(['close'])
const closeHandle = () => {
  emits('close')
}
相关推荐
程序员鱼皮15 分钟前
又被 Cursor 烧了 1 万块,我麻了。。。
前端·后端·ai·程序员·大模型·编程
孟祥_成都28 分钟前
nextjs 16 基础完全指南!(一) - 初步安装
前端·next.js
程序员爱钓鱼29 分钟前
使用简单 JSON + 自定义 t 函数实现轻量多语言国际化(无需 next-intl)
前端·javascript·trae
一 乐41 分钟前
助农平台|基于SprinBoot+vue的助农服务系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·ecmascript·springboot
vivo互联网技术43 分钟前
浅谈 AI 搜索前端打字机效果的实现方案演进
前端·vue·dom
●VON44 分钟前
Electron 小游戏实战:太空打砖块(Space Breakout)
前端·javascript·electron
重铸码农荣光1 小时前
深入理解 JavaScript 原型机制:从“如何拿到小米 SU7”说起
前端·javascript
乐观的用户1 小时前
搞懂虚拟列表实现原理与步骤
前端·vue.js
Heo1 小时前
Webpack高级之常用配置项
前端·javascript·面试
Mike_jia1 小时前
DBSyncer:开源数据同步中间件全景实战指南
前端