javascript - 在 vue.js 中保留 DOM 更新时的滚动位置

标签 javascript html 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
            })
        });
    }
}

关于javascript - 在 vue.js 中保留 DOM 更新时的滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54765451/

相关文章:

javascript - 使用 Vue 访问粘贴事件数据

Javascript 查询索引

jquery - 单击响应菜单后效果过渡更平滑

javascript - 未捕获的类型错误 : Cannot read property 'apply' of undefined when trying to call onchange() method in Vuejs

javascript - dc.js Vue 渲染图表不正确

html - 谁能告诉我为什么当我更改填充而不是其他时此列表会消失?

javascript - 删除初始化时的 d3 轴过渡

javascript - 动态生成输入类型="file"元素进行多次上传

javascript - 将 Selenium-IDE 与丰富的 Javascript 应用程序一起使用?

html - 如何仅使用内联样式删除 span 元素之间的空格?