vue3 使用 ref 的性能警告

问题

使用 ref 的性能警告 代码如下

<template>
  <div>
    <component :is="currentTabComponent"></component>
  </div>
</template>

<script setup>

import { ref,shallowRef } from "vue";
import TodoList from "./components/TodoList.vue";
import Rate from "./components/Rate.vue";

let tabs ={
  TodoList,
  Rate
}
let currentTabComponent = ref(TodoList)
</script>

警告

runtime-core.esm-bundler.js:6591 [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. Component that was made reactive:
译文:
runtime-core.esm-bundler.js:6591 [Vue 警告]:Vue 收到一个组件,该组件已成为响应式对象。这会导致不必要的性能开销,应该通过使用 markRaw 标记组件或使用 shallowRef 代替 ref 来避免。被响应的组件:

markRaw: 标记一个对象,使其永远不会转换为 proxy。返回对象本身。
shallowRef: 创建一个跟踪自身 .value 变化的 ref,但不会使其值也变成响应式的。

解决

我通过将对象标记为shallowRef解决了这个问题
因此,不要将组件存储在您的状态中,而是存储对它的键控引用,并针对对象进行查找

完整代码

<template>
  <div>
    <h1>带动画的Todolist</h1>
    <button
      v-for="(i,tab) in tabs"
      :key="i"
      :class="['tab-button', { active: currentTabComponent === tab }]"
      @click="fn(tab)"
    >
      {{ tab }}
    </button>
    <component :is="currentTabComponent"></component>
  </div>
</template>

<script setup>

import { ref,shallowRef } from "vue";
import TodoList from "./components/TodoList.vue";
import Rate from "./components/Rate.vue";

let tabs ={
  TodoList,
  Rate
}
let currentTabComponent = shallowRef(TodoList)

function fn (tab){
  currentTabComponent.value = tabs[tab]
}
</script>
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值