簡體   English   中英

在vue.js中保留DOM更新上的滾動位置

[英]Preserve scroll position on DOM update in vue.js

我有一個聊天應用程序,可加載最近的聊天消息並將其存儲在messages數組中。 以前的聊天記錄將滾動加載,並將被添加到messages數組的開頭。 載入歷史記錄時,我需要保留滾動位置

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

fetchHistory方法中,我將舊消息添加到messages數組的開頭

fetchHistory(){
    if(this.$refs.messageHistory.scrollTop == 0){
        var vm = this
        this.currentPage.prevPage().then(paginator => {
            vm.messages.unshift(...paginator.messages)
        });
    }
}

nextTick()函數中從最終高度減去初始高度,並更新滾動位置

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM