I am currently developing a frontend application using Vue 2.
Within the application, I have implemented a chat feature and enabled auto-scroll to the end of the chat on update().
An issue has arisen where the scroll action affects not only the chat box but also scrolls the entire page to that specific moment. Is there a way to override this behavior? (I will display the full code below so you can see that having a reference solely on the last message without referencing the div is not feasible - loaded_messages comes from an API array and dialogs are from WebSocket)
<template>
<div class="box col-md-8">
<div id="chat-messages" class="chat__order" style="border: 1px solid grey; overflow-y: scroll;">
<ol class="chat">
<div v-for="m in loaded_messages[0]"
direction="column"
justify-content="start"
align-items="end"
margin-left=2px
:key="m.id">
<li class="self" v-if="m.username == user">
<b-avatar :src="m.get_message_info.get_thumbnail"></b-avatar>
<div class="msg">
<p>{{m.content}}</p>
<time>{{m.get_datetime}}</time>
</div>
</li>
<li class="other" v-else>
<b-avatar :src="m.get_message_info.get_thumbnail"></b-avatar>
<div class="msg">
<p>{{m.content}}</p>
<time>{{m.get_datetime}}</time>
</div>
</li>
</div>
<div v-for="dialog in dialogs"
direction="column"
justify-content="start"
align-items="end"
:key="dialog.id">
<li class="self" v-if="dialog.username == user">
<b-avatar></b-avatar>
<div class="msg">
<p>{{dialog.message}}</p>
<time>{{dialog.datetime}}</time>
</div>
</li>
<li v-else>
<b-avatar></b-avatar>
<div class="msg">
<p>{{dialog.message}}</p>
</div>
</li>
</div>
<div ref="lastMessage"></div>
</ol>
</div>
</div>
</template>
<script>
methods: {
// Custom function for scrolling to the last message
scrollToElement() {
const [el] = this.$refs.lastMessage;
if (el) {
el.scrollIntoView({ behavior: "smooth" });
}
},
},
updated() {
this.scrollToElement();
},
</script>