vue3使用ref的性能警告問題
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: 創(chuàng)建一個跟蹤自身 .value 變化的 ref,但不會使其值也變成響應式的。
解決
我通過將對象標記為shallowRef解決了這個問題
因此,不要將組件存儲在您的狀態(tài)中,而是存儲對它的鍵控引用,并針對對象進行查找
完整代碼
<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>
vue3 ref函數用法
1.在setup函數中,可以使用ref函數,用于創(chuàng)建一個響應式數據,當數據發(fā)生改變時,Vue會自動更新UI
<template>
? ? <div>
? ? ? ? <h1>{{mycount}}</h1>
? ? ? ? <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函數僅能監(jiān)聽基本類型的變化,不能監(jiān)聽復雜類型的變化(比如對象、數組)
監(jiān)聽復雜類型的變化可以使用reactive函數
2.通過ref屬性獲取元素
vue3需要借助生命周期方法,在setup執(zhí)行時,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>總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue/cli?配置動態(tài)代理無需重啟服務的操作方法
vue-cli是vue.js的腳手架,用于自動生成vue.js+webpack的項目模板,分為vue?init?webpack-simple?項目名和vue?init?webpack?項目名兩種,這篇文章主要介紹了vue/cli?配置動態(tài)代理,無需重啟服務,需要的朋友可以參考下2022-05-05
iview table render集成switch開關的實例
下面小編就為大家分享一篇iview table render集成switch開關的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03

