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')
}
相关推荐
之歆8 小时前
Ajax 进阶:跨域、CORS、JSONP 与请求封装实战
前端·javascript·ajax
杨先生哦8 小时前
【2026 热端攻防系列 2/12】DOM 型 XSS 深度实战:AI 多态变形免杀 + 全维度防御
前端·人工智能·笔记·安全·web安全·xss
sugar__salt8 小时前
前端Ajax核心原理与实战:从异步机制到接口请求全解析
前端·javascript·ajax
问心无愧05138 小时前
ctf show web入门115
android·前端·笔记
難釋懷8 小时前
Nginx缓冲区
前端·javascript·nginx
程序猿小泓8 小时前
2026 前端面试全攻略:手写题、算法与计网/TS 高频考点
前端·javascript·css
JustHappy16 小时前
古法编程秘籍(七):互联网到底是什么?把两台电脑怎么说话搞懂就够了
前端·后端·网络协议
snow@li16 小时前
SEO-文章标题:写文章时候,分类+主标题+大纲+解释 作为标题 / 不点进去也知道全文覆盖什么 / 标题即架构
前端
kyriewen17 小时前
Git Commit 前自动修复代码风格?配置 Husky + lint-staged,从此 CR 只聊逻辑
前端·git·面试
小和尚同志18 小时前
AI 自动化测试探索(一):Playwright MCP
前端·人工智能·aigc