[英]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.