
vue 滚动到顶部时加载更多数据,但保持滚动位置不变
在某些场景中,我们需要类似微信聊天记录那样,当用户向上滚动到顶部时加载更多历史记录,但滚动条位置依然保持在当前位置。
下面提供一种解决方法:
- {{ item }}
import { createApp, ref, nextTick } from 'vue'
createApp({
setup() {
const msgs = ref([])
const chatListRef = ref()
const scrollToBottom = async () => {
const chatListElement = chatListRef.value
if (chatListElement) {
chatListElement.scrollTop = chatListElement.scrollHeight
}
}
const handleScroll = (ev) => {
const target = event.target
if (target.scrollTop === 0) {
// TODO: 加载更多数据
alert('添加完数据后希望停留在当前数据的位置,而不是最顶部')
}
}
nextTick(() => {
scrollToBottom()
})
return {
msgs,
chatListRef,
handleScroll
}
}
}).mount('#app')当向上滚动到顶部时,handlescroll 函数会被触发,此时可以判断 scrolltop 是否为 0,如果是,则加载更多数据并更新 msgs 数组。关键在于,在加载更多数据后,需要调用 scrolltobottom 函数将滚动条位置调整回当前位置。
立即学习“前端免费学习笔记(深入)”;
请注意,你可以根据需要修改 scrolltobottom 函数中的滚动行为。










