Currently, I am in the process of developing a real-time chat application using Vue.js and Firebase's real-time database.
One specific functionality I am attempting to implement is ensuring that the chat window automatically scrolls to the bottom whenever a new message is received. To accomplish this, I've created a watcher for monitoring changes in the conversation data. However, I'm encountering an issue where the function within the watcher is triggered before the DOM has finished updating, resulting in an incorrect scroll value. I am considering watching another property or finding a way to detect when the new data has been fully loaded into the DOM. Any suggestions on how to tackle this challenge effectively?
Here is the snippet of the HTML code:
<div class="chat" ref="chat">
<div
v-for="(message,key) in conversations" :key="key">
<div class="message">
{{message.text}}
</div>
</div>
</div>
Here is the script section utilizing VueFire:
const conversations = db.ref('conversations');
export default {
data() {
return {
conversations: {},
}
},
watch: {
conversations: function() {
//Scroll to bottom when new message received
this.$refs.chat.scrollTop = this.$refs.chat.scrollHeight;
}
}
}
I have managed to temporarily address this issue by incorporating a timeout, although I personally consider it a bit hacky...
setTimeout(() => {
this.$refs.chat.scrollTop = this.$refs.chat.scrollHeight;
}, 300);
Your guidance and assistance with resolving this matter would be greatly appreciated. Thank you.