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')
}
相关推荐
小菜今天没吃饱4 分钟前
DVWA-XSS(stored)
前端·网络安全·xss·dvwa
云飞云共享云桌面4 分钟前
研发部门使用SolidWorks,三维设计云桌面应该怎么选?
运维·服务器·前端·网络·自动化·电脑
老华带你飞13 分钟前
茶叶商城|基于SprinBoot+vue的茶叶商城系统(源码+数据库+文档)
java·前端·javascript·数据库·vue.js·spring boot
烛阴15 分钟前
不只是Public与Private:C#访问修饰符全方位解读
前端·c#
涔溪19 分钟前
Vue3常用的组合式API 超详细讲解
前端·javascript·vue.js
秋邱20 分钟前
AR + 离线 AI 实战:YOLOv9+TensorFlow Lite 实现移动端垃圾分类识别
开发语言·前端·数据库·人工智能·python·html
蜡笔小嘟20 分钟前
使用gemini 3 pro实现可视化大屏
前端·ai·gemini·gemini3peo
马玉霞25 分钟前
vue3很丝滑的table表格向上滚动效果,多用于统计页面
前端·vue.js
用户9520816117926 分钟前
百度地图JSAPI THREE Label 组件使用指南,轻松实现地图标签渲染
前端
SVIP1115930 分钟前
webpack入门 精细版
前端·webpack·node.js