使用場景一:當(dāng)組件進(jìn)入視窗時再進(jìn)行加載
假設(shè)頁面中有三個組件A、B、C
C組件中有一張圖片
<template>
<div class="A">
<A></A>
</div>
<div class="B">
<B></B>
</div>
<div>
<C></C>
</div>
</template>
<script setup>
import A from './components/A.vue'
import B from './components/B.vue'
import C from './components/C.vue'
</script>
打開頁面:
?文章來源:http://www.zghlxwxcb.cn/news/detail-461424.html
如果一個頁面中的內(nèi)容非常多,用戶再首次打開時并沒有瀏覽到下方的內(nèi)容,但頁面必須加載完下方的內(nèi)容才會顯示,這無疑非常影響性能
接下來我們做一些調(diào)整
defineAsyncComponent
創(chuàng)建一個只有在需要時才會加載的異步組件。
?defineAsyncComponent是vue3提供的內(nèi)置api。用于異步加載組件
但是僅靠這個api并不能完成我們所需要的功能
這里我們還需要借助vueUse中的一個api?
首先我們需要安裝一下vueUse的依賴
npm i @vueuse/core
我們需要使用vueUse中的useIntersectionObserver?
?安裝完成后來修改一下我們的代碼:
<template>
<div class="A">
<A></A>
</div>
<div class="B">
<B></B>
</div>
<div ref="target">
<C v-if="targetIsVisible"></C>
</div>
</template>
<script setup>
import A from './components/A.vue'
import B from './components/B.vue'
import { defineAsyncComponent, ref } from 'vue';
import { useIntersectionObserver } from '@vueuse/core'
const C = defineAsyncComponent(() => //異步引入組件
import('./components/C.vue')
)
const target = ref(null) //獲取需要操作的dom元素
const targetIsVisible = ref(false) //定義一個dom元素顯示與隱藏開關(guān)
const { stop } = useIntersectionObserver( //定義一個函數(shù)用于控制
target,
([{ isIntersecting }]) => { //這里的isIntersecting表示的是dom元素是否進(jìn)入視窗,值為true或flase
console.log(isIntersecting);
if (isIntersecting) {
targetIsVisible.value = isIntersecting //將isIntersecting賦值給開關(guān),即表示進(jìn)入視窗就顯示該dom元素
}
},
)
</script>
?
?
?
?
這樣就實現(xiàn)了異步加載C組件,在頁面視窗滾動到C組件時才會加載C組件。文章來源地址http://www.zghlxwxcb.cn/news/detail-461424.html
到了這里,關(guān)于vue3中實現(xiàn)異步組件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!