3

I have a chat application which loads the recent chat messages and store them in messages array. Previous chat history is loaded on scroll and will be added to the beginning of messages array. I need to preserve the scroll position when history is loaded

//chat.vue
<div ref="chatHistory" @scroll="fetchHistory">
    <div v-for="item in messages" :key="item.id">
        <span>{{item.body}}</span>              
    </div>
</div>

In fetchHistory method, I add the old messages to beginning of messages array

fetchHistory(){
    if(this.$refs.messageHistory.scrollTop == 0){
        var vm = this
        this.currentPage.prevPage().then(paginator => {
            vm.messages.unshift(...paginator.messages)
        });
    }
}
LJP
  • 1,811
  • 4
  • 23
  • 34

1 Answers1

9

Subtract initial height from final height in nextTick() function and update scroll position

fetchHistory(){
    if(this.$refs.messageHistory.scrollTop == 0){
        var initialHeight = this.$refs.messageHistory.scrollHeight
        var vm = this
        this.currentPage.prevPage().then(paginator => {
            vm.messages.unshift(...paginator.messages)
            vm.$nextTick(() => {
              vm.$refs.messageHistory.scrollTop = vm.$refs.messageHistory.scrollHeight - initialHeight
            })
        });
    }
}
LJP
  • 1,811
  • 4
  • 23
  • 34