Appearance
ScrollObserver Component Code
Dependencies
This component requires:
- Vue 3 with Composition API
- Browser support for Intersection Observer API
Full Component Code
vue
<script setup>
import { ref, onMounted } from 'vue'
const emit = defineEmits(['scrolledToEnd'])
let observer = ref(null)
const root = ref(null)
// let page = ref(0)
onMounted(() => {
observer.value = new IntersectionObserver(([entry]) => {
if (entry && entry.isIntersecting) {
emit('scrolledToEnd')
}
})
observer.value.observe(root.value)
})
</script>
<template>
<div ref="root" class="observer"></div>
</template>
<style>
.observer {
height: 1px;
}
</style>How It Works
The ScrollObserver component uses the Intersection Observer API to detect when an element enters the viewport. Here's how it works:
- The component creates a minimal div element with a height of 1px
- On mount, it initializes an Intersection Observer that watches this div
- When the div becomes visible (enters the viewport), the observer's callback is triggered
- The component emits a
scrolledToEndevent that parent components can listen for - Parent components can use this event to load more content, implement infinite scrolling, etc.
Usage with OTable
This component is used by the OTable component to provide infinite scrolling functionality. The OTable includes this component at the bottom of its content and listens for the scrolledToEnd event to load more data.
vue
<!-- Inside OTable.vue -->
<template>
<div class="table-wrapper">
<table>
<!-- Table content -->
</table>
<OScrollObserver
v-if="enableInfiniteScroll"
@scrolledToEnd="(...args) => handelLoadMoreData(emits)"
/>
</div>
</template>