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')
}
相关推荐
GISer_Jing20 分钟前
Node.js中如何修改全局变量的几种方式
前端·javascript·node.js
秋意钟36 分钟前
Element UI日期选择器默认显示1970年解决方案
前端·javascript·vue.js·elementui
我命由我123451 小时前
微信小程序 - 自定义实现分页功能
前端·微信小程序·小程序·前端框架·html·html5·js
程序员黄同学2 小时前
请谈谈 Vue 中的 key 属性的重要性,如何确保列表项的唯一标识?
前端·javascript·vue.js
繁依Fanyi2 小时前
巧妙实现右键菜单功能,提升用户操作体验
开发语言·前端·javascript·vue.js·uni-app·harmonyos
前端御书房2 小时前
前端防重复请求终极方案:从Loading地狱到精准拦截的架构升级
前端·javascript
web182854825122 小时前
nginx 部署前端vue项目
前端·vue.js·nginx
zy0101012 小时前
HTML标签
前端·css·html
程序员黄同学2 小时前
解释 Vue 中的虚拟 DOM,如何通过 Diff 算法最小化真实 DOM 更新次数?
开发语言·前端·javascript
蓝谷芮济3 小时前
二:前端发送POST请求,后端获取数据
前端