使用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 avoid by marking 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>
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的效能警告問題怎麼解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!