vue3告警:用markRaw或者shallowRef代替ref

8,702 阅读1分钟

- 警告:

vue3 使用 component :is="comMap[comNum]" 的时候报错警告⚠

<script setup>
import { reactive } from "vue";
import HelloWorld from "./components/HelloWorld.vue";
import MoreList from "./components/MoreList.vue";
import AsyncAwait from "./components/AsyncAwait.vue";

const comMap = reactive([MoreList, AsyncAwait]);

const comNum = 0;
</script>

<template>
    <component :is="comMap[comNum]" />
</template>

App.vue:14 [Vue warn]: 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.

image.png

- 来自百度的翻译:

Vue收到了一个组件,该组件被制成了一个反应对象。这可能会导致不必要的性能开销,应该通过用“markRaw”标记组件或使用“shallowRef”而不是“ref”来避免。

- 解决方案:

使用 markRaw 标记引入的组件既可!

<script setup>
import { reactive, markRaw } from "vue";
import HelloWorld from "./components/HelloWorld.vue";
import MoreList from "./components/MoreList.vue";
import AsyncAwait from "./components/AsyncAwait.vue";

const comMap = reactive([markRaw(MoreList), markRaw(AsyncAwait)]);

const comNum = 0;
</script>

<template>
    <component :is="comMap[comNum]" />
</template>