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 分钟前
CSS高频属性速查指南
前端·css·css3
小高0074 分钟前
🌐AST(抽象语法树):前端开发的“代码编译器”
前端·javascript·面试
蓝易云4 分钟前
Git stash命令的详细使用说明及案例分析。
前端·git·后端
GIS瞧葩菜6 分钟前
Cesium 中拾取 3DTiles 交点坐标
前端·javascript·cesium
Allen Bright7 分钟前
【JS-7-ajax】AJAX技术:现代Web开发的异步通信核心
前端·javascript·ajax
轻语呢喃11 分钟前
Mock : 没有后端也能玩的虚拟数据
前端·javascript·react.js
Dnui_King15 分钟前
Oracle 在线重定义
java·服务器·前端
西柚啊27 分钟前
AI + 可视化:Stagewise 如何让前端 UI 调试效率飞跃
前端·ai编程
中微子29 分钟前
解决跨域问题的古早方法JSONP
前端
林太白1 小时前
Rust详情修改删除优化
前端·后端·rust