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 创建的引用不会将组件标记为响应式对象,从而避免了潜在的性能开销。 

<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>

切换组件不能做全局相关操作,例如关闭当前页面,需要子传父调用

父:
<component :is="activeComponent" @close="handleClose" />

function handleClose() {
  window.close()
}

子:
const emits = defineEmits(['close'])
const closeHandle = () => {
  emits('close')
}

 

 

相关推荐

  1. Vue3使用动态组件

    2024-02-01 16:56:02       40 阅读
  2. Vue3使用component动态展示组件

    2024-02-01 16:56:02       8 阅读
  3. vue3在router中使用pinia解决

    2024-02-01 16:56:02       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-01 16:56:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-01 16:56:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-01 16:56:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-01 16:56:02       20 阅读

热门阅读

  1. 小白Linux学习笔记-1.基础命令

    2024-02-01 16:56:02       24 阅读
  2. MySQL必看表设计经验汇总-下(精华版)

    2024-02-01 16:56:02       41 阅读
  3. 代码随想录算法训练营第六天 - 哈希表part02

    2024-02-01 16:56:02       28 阅读
  4. 超时引发的牛角尖一(hystrix概述)

    2024-02-01 16:56:02       28 阅读
  5. Python爬虫存储库安装

    2024-02-01 16:56:02       32 阅读
  6. 【C语言】【力扣】刷题小白的疑问

    2024-02-01 16:56:02       29 阅读
  7. 美国服务器地址和端口及密码

    2024-02-01 16:56:02       32 阅读