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 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
爱喝白开水a10 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌4110 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
吃杠碰小鸡11 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone11 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_090111 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农11 小时前
Vue 2.3
前端·javascript·vue.js
夜郎king12 小时前
HTML5 SVG 实现日出日落动画与实时天气可视化
前端·html5·svg 日出日落
夏幻灵13 小时前
HTML5里最常用的十大标签
前端·html·html5
Mr Xu_13 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js