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')
}
相关推荐
OpenTiny社区2 分钟前
TinyRobot Skills技巧大公开:让 AI 成为你的 “UI 搭建”副驾驶
前端·vue.js·ai编程
土豆12505 分钟前
Rust 实战:手把手教你开发一个命令行工具
前端·rust
Moment9 分钟前
2026年,TypeScript还值不值得学 ❓❓❓
前端·javascript·面试
林九生12 分钟前
【Vue3】解决 Tailwind CSS v4 + Vite 8 中 `@import “tailwindcss“` 不起作用的问题
前端·css
陈随易13 分钟前
AI时代,说点心里话
前端·后端·程序员
console.log('npc')23 分钟前
Cursor,Trae,Claude Code如何协作生产出一套前后台app?
前端·人工智能·react.js·设计模式·ai·langchain·ai编程
乌拉那拉丹36 分钟前
vue3 配置跨域 (vite.config.ts中配置)
前端·vue.js
happymaker062639 分钟前
web前端学习日记——DAY01(HTML基本标签)
前端·学习·html
笨笨狗吞噬者43 分钟前
【uniapp】小程序支持分包引用分包 node_modules 依赖产物打包到分包中
前端·微信小程序·uni-app
悟空瞎说1 小时前
Electron 踩坑实录:主窗口 icon 配置了,打包 Windows 后死活不显示?(全网最细排查+解决方案)
前端