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')
}
相关推荐
我的写法有点潮16 分钟前
JS中对象是怎么运算的呢
前端·javascript·面试
悠哉摸鱼大王17 分钟前
NV12 转 RGB 完整指南
前端·javascript
一壶纱18 分钟前
UniApp + Pinia 数据持久化
前端·数据库·uni-app
双向3319 分钟前
【RAG+LLM实战指南】如何用检索增强生成破解AI幻觉难题?
前端
海云前端120 分钟前
前端人必懂的浏览器指纹:不止是技术,更是求职加分项
前端
青莲84321 分钟前
Java内存模型(JMM)与JVM内存区域完整详解
android·前端·面试
parade岁月25 分钟前
把 Git 提交变成“可执行规范”:Commit 规范体系与 Husky/Commitlint/Commitizen/Lint-staged 全链路介绍
前端·代码规范
青莲84325 分钟前
Java内存回收机制(GC)完整详解
java·前端·面试
pas13626 分钟前
29-mini-vue element搭建更新
前端·javascript·vue.js
IT=>小脑虎32 分钟前
2026版 React 零基础小白进阶知识点【衔接基础·企业级实战】
前端·react.js·前端框架