您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

vue3使用ref的性能警告问题怎么解决

2025/11/17 13:54:14发布24次查看
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> <h2>带动画的todolist</h2> <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>
vue3 ref函数用法1.在setup函数中,可以使用ref函数,用于创建一个响应式数据,当数据发生改变时,vue会自动更新ui
<template> <div> <h2>{{mycount}}</h2> <button @click="changemycount">changemycount</button> </div></template> <script>import { ref } from "vue";export default { name: "ref", setup(){ const mycount = ref(2); const changemycount = ()=>{ mycount.value = mycount.value + 2 ; } return { mycount, changemycount, } }};</script>
ref函数仅能监听基本类型的变化,不能监听复杂类型的变化(比如对象、数组)
监听复杂类型的变化可以使用reactive函数
2.通过ref属性获取元素
vue3需要借助生命周期方法,在setup执行时,template中的元素还没挂载到页面上,所以必须在mounted之后才能获取到元素。
<template> <div> <div ref="box"><button>hehe</button></div> </div></template> <script>import { ref } from "vue";export default { name: "ref", setup(){ const box = ref(null) onmounted(()=>{ console.log(box.value) }) }};</script>
以上就是vue3使用ref的性能警告问题怎么解决的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product