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')
}
相关推荐
JianZhen✓10 分钟前
面试题名词解析一
前端
会跑的葫芦怪12 分钟前
Web3开发中的前端、后端与合约:角色定位与协作逻辑
前端·web3·区块链
江城开朗的豌豆15 分钟前
TypeScript泛型:让类型也"通用"的魔法
前端·javascript
江城开朗的豌豆26 分钟前
TypeScript函数:给JavaScript函数加上"类型安全带"
前端·javascript
凌览27 分钟前
Node.js + Python 爬虫界的黄金搭档
前端·javascript·后端
Java 码农33 分钟前
vue 使用vueCli 搭建vue2.x开发环境,并且指定ts 和less
前端·vue.js·less
欧阳码农44 分钟前
AI提效这么多,为什么不试试自己开发N个产品呢?
前端·人工智能·后端
chenbin___1 小时前
Omit<>的用法
开发语言·前端·javascript
嫂子的姐夫1 小时前
21-webpack介绍
前端·爬虫·webpack·node.js
IT_陈寒1 小时前
SpringBoot 3.x 中被低估的10个隐藏特性,让你的开发效率提升50%
前端·人工智能·后端