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')
}
相关推荐
芒果茶叶44 分钟前
并行SSR,SSR并行加载
前端·javascript·架构
vortex51 小时前
解决 Kali 中 Firefox 下载语言包和插件速度慢的问题:配置国内镜像加速
前端·firefox·腾讯云
修仙的人1 小时前
Rust + WebAssembly 实战!别再听说,学会使用!
前端·rust
maxine1 小时前
JS Entry和 HTML Entry
前端
用户63310776123661 小时前
Who is a Promise?
前端
比老马还六2 小时前
Blockly元组积木开发
前端
笨笨狗吞噬者2 小时前
【uniapp】小程序体积优化,JSON文件压缩
前端·微信小程序·uni-app
西洼工作室2 小时前
浏览器事件循环与内存管理可视化
前端·javascript·css·css3
xier1234562 小时前
高性能和高灵活度的react表格组件
前端
你打不到我呢2 小时前
nestjs入门:上手数据库与prisma
前端