1.動態(tài)組件
<template>
<div>
<h1>組件切換</h1>
<component :is="currentComponent"></component>
<button @click="toggleComponent">點擊切換組件</button>
</div>
</template>
<script setup lang="ts">
import { markRaw, shallowRef } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
const currentComponent = shallowRef(markRaw(ComponentA));
const toggleComponent = () => {
currentComponent.value = currentComponent.value === ComponentA ? markRaw(ComponentB) : markRaw(ComponentA);
};
</script>
<!-- markRaw 方法用于將一個對象標記為 "原始",從而告訴 Vue 不需要將其轉換為響應式對象。標記為 "原始" 的對象在響應式系統(tǒng)中不會被追蹤更改,這可以幫助避免不必要的性能開銷。
shallowRef 是用于創(chuàng)建一個淺的響應式引用的方法。與 ref 創(chuàng)建的響應式引用不同,shallowRef 不會對其內部對象進行深度觀察,而只觀察引用本身的變化。這意味著只有當引用本身發(fā)生變化時,才會觸發(fā)更新,而不會遞歸觀察引用內部對象的變化。
這兩個方法通常用于特定場景下的性能優(yōu)化。
在上述修改代碼的例子中,我們使用 markRaw 將組件標記為非響應式的,避免了不必要的性能開銷。而使用 shallowRef 創(chuàng)建淺的響應式引用,只觀察引用本身的變化,而不觀察組件內部的變化。這樣可以保證在切換組件時,只有引用本身變化時才會觸發(fā)組件的更新,提高了性能效率。 -->
當使用 <component :is="..."> 來在多個組件間作切換時,被切換掉的組件會被卸載。我們可以通過 <KeepAlive>組件強制被切換掉的組件仍然保持“存活”的狀態(tài)。文章來源:http://www.zghlxwxcb.cn/news/detail-715333.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-715333.html
2.異步組件
<template>
<div>
<h1>組件切換</h1>
<Keep-alive><component :is="currentComponent"></component></Keep-alive>
<button @click="toggleComponent">點擊切換組件</button>
</div>
</template>
<script setup lang="ts">
import { markRaw, shallowRef } from 'vue';
import ComponentA from './components/ComponentA.vue';
import { defineAsyncComponent } from 'vue'
const ComponentB =defineAsyncComponent(()=>import ("./components/ComponentB.vue"))
const currentComponent = shallowRef(markRaw(ComponentA));
const toggleComponent = () => {
currentComponent.value = currentComponent.value === ComponentA ? markRaw(ComponentB) : markRaw(ComponentA);
};
</script>
<!-- markRaw 方法用于將一個對象標記為 "原始",從而告訴 Vue 不需要將其轉換為響應式對象。標記為 "原始" 的對象在響應式系統(tǒng)中不會被追蹤更改,這可以幫助避免不必要的性能開銷。
shallowRef 是用于創(chuàng)建一個淺的響應式引用的方法。與 ref 創(chuàng)建的響應式引用不同,shallowRef 不會對其內部對象進行深度觀察,而只觀察引用本身的變化。這意味著只有當引用本身發(fā)生變化時,才會觸發(fā)更新,而不會遞歸觀察引用內部對象的變化。
這兩個方法通常用于特定場景下的性能優(yōu)化。
在上述修改代碼的例子中,我們使用 markRaw 將組件標記為非響應式的,避免了不必要的性能開銷。而使用 shallowRef 創(chuàng)建淺的響應式引用,只觀察引用本身的變化,而不觀察組件內部的變化。這樣可以保證在切換組件時,只有引用本身變化時才會觸發(fā)組件的更新,提高了性能效率。 -->
到了這里,關于vue3 動態(tài)組件和異步組件的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!