I'm currently working on a chat page. Within this page, there is a div element that serves as the message container. As users scroll up, a request is sent to the server to retrieve older messages, which are then added to the beginning of the message container. However, an issue arises where the user's scrolling position suddenly changes when new messages are added. Here is the function for getting messages:
this.$refs.messages.addEventListener("scroll", () => { //add event listener to messages container
if (this.$refs.messages.scrollTop < 90) {
this.loadingGetMoreMessages = true
this.getMoreMessages() // get older messages and add them in all messages array
}
})
Vue structure:
<div class="d-flex flex-column gap-2 h-100 w-100 pt-3" style="overflow-y: auto; overflow-x: hidden"
ref="messages">
<div v-for="(message, index) in chat.messages" :key="index">
<div :class="{ 'message-container': true, 'flex-row-reverse': !message.yours }"
:ref="'m-' + message.message_id">
<div class="d-flex gap-2" :style="{ 'padding-right': !message.yours ? '20px' : '' }">
<div :class="{ 'your-message': message.yours, 'its-message': !message.yours }">
{{ message.message }}
<div class="d-flex align-items-center gap-2">
<i class="text-muted fi fi-br-check d-flex" v-if="!message.seen && message.yours"></i>
<i class="text-muted fi fi-br-check-double d-flex"
v-if="message.seen && message.yours"></i>
<p class="text-muted mt-1" style="font-size: .8rem"> {{ message.time }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
The goal is to ensure that adding new messages at the beginning of the div does not disrupt the user's scroll position