最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Preserve scroll position on DOM update in vue.js - Stack Overflow

programmeradmin0浏览0评论

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
            })
        });
    }
}
发布评论

评论列表(0)

  1. 暂无评论