
vue 滚动到顶部时加载更多数据,但保持滚动位置不变
在某些场景中,我们需要类似微信聊天记录那样,当用户向上滚动到顶部时加载更多历史记录,但滚动条位置依然保持在当前位置。
下面提供一种解决方法:
<div class="container" @scroll="handlescroll" ref="chatlistref">
<ul>
<li v-for="item in msgs">{{ item }}</li>
</ul>
</div>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 函数中的滚动行为。
以上就是Vue中如何实现滚动到顶部加载更多数据且保持滚动位置不变?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号