feat(MediaCard): implement lazy loading for API calls

This commit is contained in:
InfinityPacer
2024-12-23 02:47:37 +08:00
parent a469282730
commit 79c606370c
+40 -2
View File
@@ -67,6 +67,12 @@ const sourceIconDict: { [key: string]: any } = {
bangumi: bangumiImage, bangumi: bangumiImage,
} }
// 绑定MediaCard元素
const mediaCardRef = ref<HTMLElement | null>(null)
// 创建Intersection Observer实例
const observer = ref<IntersectionObserver | null>(null)
// 获得mediaid // 获得mediaid
function getMediaId() { function getMediaId() {
if (props.media?.tmdb_id) return `tmdb:${props.media?.tmdb_id}` if (props.media?.tmdb_id) return `tmdb:${props.media?.tmdb_id}`
@@ -359,10 +365,40 @@ function handleSearch() {
}) })
} }
// 装载时检查是否已订阅 // 懒加载检查
onBeforeMount(() => { function handleCheckLazy() {
handleCheckSubscribe() handleCheckSubscribe()
handleCheckExists() handleCheckExists()
}
// 在元素进入视窗时触发懒加载函数
function setupIntersectionObserver() {
if (mediaCardRef.value) {
observer.value = new IntersectionObserver(
entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// 只要MediaCard进入视窗,就调用懒加载的操作
handleCheckLazy()
// 加载后销毁观察者实例
observer.value?.disconnect()
observer.value = null
}
})
},
{ threshold: 0.1 },
)
observer.value.observe(mediaCardRef.value)
}
}
onMounted(() => {
setupIntersectionObserver()
})
onBeforeUnmount(() => {
observer.value?.disconnect()
observer.value = null
}) })
// 计算图片地址 // 计算图片地址
@@ -407,6 +443,7 @@ function onRemoveSubscribe() {
<template> <template>
<VHover> <VHover>
<template #default="hover"> <template #default="hover">
<div ref="mediaCardRef">
<VCard <VCard
v-bind="hover.props" v-bind="hover.props"
:height="props.height" :height="props.height"
@@ -483,6 +520,7 @@ function onRemoveSubscribe() {
<VImg cover :src="sourceIconDict[props.media?.source]" class="shadow-lg" /> <VImg cover :src="sourceIconDict[props.media?.source]" class="shadow-lg" />
</VAvatar> </VAvatar>
</VCard> </VCard>
</div>
</template> </template>
</VHover> </VHover>
<!-- 订阅季弹窗 --> <!-- 订阅季弹窗 -->