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')
}
相关推荐
踩着两条虫38 分钟前
VTJ.PRO的平台介绍与特性
前端·架构·ai编程
光影少年1 小时前
前端工程化升级
前端·javascript·react.js·前端框架
Hello--_--World1 小时前
节流 VS 防抖 相关知识点与面试题
前端·javascript
We་ct1 小时前
AI辅助开发术语体系深度剖析
开发语言·前端·人工智能·ai·ai编程
去伪存真1 小时前
Superpowers 从“调教提示词”转向“构建工程规范”
前端·agent
发现一只大呆瓜1 小时前
深度起底 Vite:从打包流程到插件钩子执行时序的全链路解析
前端·vite
jserTang1 小时前
Claude Code 源码深度解析 - 前言
前端·javascript·后端
hehelm1 小时前
vector模拟实现
前端·javascript·算法
|晴 天|2 小时前
[特殊字符]️ Vue 3项目架构设计:从2200行单文件到24个组件
前端·javascript·vue.js
FrontAI2 小时前
深入浅出 LangChain —— 第三章:模型抽象层
前端·人工智能·typescript·langchain·ai agent