|
| 1 | +<script setup lang="ts"> |
| 2 | +import { onMounted, ref, onUnmounted } from 'vue' |
| 3 | +import { prefixed } from '@linzhe-tools/shared' |
| 4 | +
|
| 5 | +const name = 'infinite-scroll' |
| 6 | +
|
| 7 | +const props = defineProps({ |
| 8 | + // 当最后一个元素滚动到 <= distance到视窗时,触发新的加载 |
| 9 | + // 但因为额外的检测底部96px{假设的distance} >= 新的元素的合计的高度,则这个一直在视窗内,不会触发检测了 |
| 10 | + // 根据实际情况谨慎设置 |
| 11 | + //! not watch this prop[distance] to rehandle |
| 12 | + distance: Number, |
| 13 | + onScrollBottom: Function, |
| 14 | +}) |
| 15 | +
|
| 16 | +const wrapperRef = ref<HTMLElement | null>(null) |
| 17 | +const contentRef = ref<HTMLElement | null>(null) |
| 18 | +const placeholderRef = ref<HTMLElement | null>(null) |
| 19 | +
|
| 20 | +let enableCheckScrollBottom = false |
| 21 | +
|
| 22 | +let observer: IntersectionObserver | null = null |
| 23 | +const pendingOnScrollBottom = ref(false) |
| 24 | +onMounted(() => { |
| 25 | + if (contentRef.value && wrapperRef.value) { |
| 26 | + const wrapperHeight = wrapperRef.value.getBoundingClientRect().height |
| 27 | + const contentHeight = contentRef.value.getBoundingClientRect().height |
| 28 | + enableCheckScrollBottom = wrapperHeight < contentHeight |
| 29 | + const options: IntersectionObserverInit = { root: wrapperRef.value } |
| 30 | + if (props.distance) { |
| 31 | + options.rootMargin = `0px 0px ${props.distance}px 0px` |
| 32 | + } |
| 33 | +
|
| 34 | + observer = new IntersectionObserver(async (entries) => { |
| 35 | + const entry = entries[0] |
| 36 | + if (pendingOnScrollBottom.value === false) { |
| 37 | + if ( |
| 38 | + entry.isIntersecting && |
| 39 | + props.onScrollBottom && |
| 40 | + enableCheckScrollBottom |
| 41 | + ) { |
| 42 | + pendingOnScrollBottom.value = true |
| 43 | + await props.onScrollBottom() |
| 44 | + pendingOnScrollBottom.value = false |
| 45 | + } |
| 46 | + } |
| 47 | + }, options) |
| 48 | + observer.observe(placeholderRef.value!) |
| 49 | + } |
| 50 | +}) |
| 51 | +onUnmounted(() => { |
| 52 | + if (observer) { |
| 53 | + observer.disconnect() |
| 54 | + } |
| 55 | +}) |
| 56 | +</script> |
| 57 | + |
| 58 | +<template> |
| 59 | + <div :class="`${prefixed}-${name}-wrapper`" ref="wrapperRef"> |
| 60 | + <div :class="`${prefixed}-${name}-content`" ref="contentRef"> |
| 61 | + <slot></slot> |
| 62 | + </div> |
| 63 | + <div |
| 64 | + :class="`${prefixed}-${name}-bottom-placeholder`" |
| 65 | + ref="placeholderRef" |
| 66 | + ></div> |
| 67 | + <slot v-if="pendingOnScrollBottom" name="pendingOnScrollBottom"></slot> |
| 68 | + </div> |
| 69 | +</template> |
| 70 | +<style> |
| 71 | +.linzhe-tools-infinite-scroll-wrapper { |
| 72 | + height: 100%; |
| 73 | + overflow-y: auto; |
| 74 | +} |
| 75 | +</style> |
0 commit comments