In this episode, we're tackling the problem of knowing when the user has scrolled to the top of the chat message list so we can load more (previous) messages. To do this, we use the Intersection Observer API, but instead of setting it up manually (which can get a bit messy), we leverage the awesome @vueuse/core
composable – it makes the whole process much simpler and more "Vue-friendly".
We start by inserting a small, invisible element at the top of our message list. This element acts like a watcher: when it comes into view as the user scrolls up, that's our cue to load more messages. There's a bit of fiddling with flex layout direction since we're displaying the messages in reverse order. We create a ref for our target element, set up the observer using VueUse's useIntersectionObserver
composable, and hook up a callback that logs whenever the observer is triggered.
We then refine the experience by nudging the observer element down a bit with some CSS. This way, new messages can load before the user actually reaches the very top, making scrolling feel smoother and more responsive. After testing that everything is being triggered at the right moment, we clean up the UI so there's nothing visible to users.
The groundwork is all set! In the next episode, we'll connect this detection to actually fetching (and displaying) the next chunk of messages from our backend. If you're building an infinite scroll chat or message list, this technique is for you.