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')
}
相关推荐
mfxcyh2 分钟前
Vue3 右键菜单实现方案(基于 vue3-context-menu)
前端
treesforest2 分钟前
从IP地址归属地查询到IP地理位置精准查询指南
服务器·前端·网络
LF男男9 分钟前
WindmillBullect.cs
前端
小白学大数据11 分钟前
Python 爬虫爬取应用商店数据:请求构造与数据解析
前端·爬虫·python·数据分析
pkowner19 分钟前
若依分页问题及解决方法
java·前端·算法
golang学习记26 分钟前
Cursor官方团队的AI指南:Cursor Team Kit
前端·cursor
Lee川31 分钟前
RAG 知识库问答:从概念到代码的完整实现
前端·人工智能·后端
计算机安禾1 小时前
【c++面向对象编程】第22篇:输入输出运算符重载:<< 与 >> 的友元实现
java·前端·c++
redreamSo1 小时前
14 小时烧光 200 美金:Codex 和 Claude 的 /goal 命令打开了"放手跑"模式
前端
TingTing1 小时前
Webpack5 前端工程化建设
前端