You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

69 lines
1.8 KiB

<template>
<div ref="scrollContainer">
<slot />
<div ref="sentinel" style="height: 1px"></div>
</div>
</template>
<script lang="ts">
import { Component, Emit, Prop, Vue } from "vue-facing-decorator";
@Component
export default class InfiniteScroll extends Vue {
@Prop({ default: 200 })
readonly distance!: number;
private observer!: IntersectionObserver;
private isInitialRender = true;
private isLoading = false;
private debounceTimeout: number | null = null;
updated() {
if (!this.observer) {
const options = {
root: null,
rootMargin: `0px 0px ${this.distance}px 0px`,
threshold: 1.0,
};
this.observer = new IntersectionObserver(
this.handleIntersection,
options,
);
this.observer.observe(this.$refs.sentinel as HTMLElement);
}
}
// 'beforeUnmount' hook runs before unmounting the component
beforeUnmount() {
if (this.observer) {
this.observer.disconnect();
}
if (this.debounceTimeout) {
window.clearTimeout(this.debounceTimeout);
}
}
@Emit("reached-bottom")
handleIntersection(entries: IntersectionObserverEntry[]) {
const entry = entries[0];
if (entry.isIntersecting && !this.isLoading) {
// Debounce the intersection event
if (this.debounceTimeout) {
window.clearTimeout(this.debounceTimeout);
}
this.debounceTimeout = window.setTimeout(() => {
this.isLoading = true;
this.$emit("reached-bottom", true);
// Reset loading state after a short delay
setTimeout(() => {
this.isLoading = false;
}, 1000);
}, 300);
}
return false;
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>