admin管理员组

文章数量:1315377

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)
        });
    }
}

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)
        });
    }
}
Share Improve this question asked Feb 19, 2019 at 11:38 LJPLJP 1,9515 gold badges25 silver badges36 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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
            })
        });
    }
}

本文标签: javascriptPreserve scroll position on DOM update in vuejsStack Overflow