1.实现效果:
列表滚动
2.代码+解析
思路:1.拿到接口返回的所有列表数据,通过分页新建数组用于展示播放的数据。2.每次展示一页数据,快展示完毕(自己定义这个位置)就在展示数组中新增一页,当第一页的最后一条数据滚动过可视区域后就删除原来的一页数据,依次新增数据,并调整滚动位置。3.利用最重要的工具,定时器!setInterval
// 滚动容器的引用
const scrollContainer = ref(null)
// 存储展示的异常记录数据
const gissWarnInfoData = ref([])
//接口拿出来的总数据
const gissWarnInfoTotal = ref([])
// 当前页码,初始为 1
const currentPage = ref(1)
// 每页显示的条数
const pageSize = ref(10)
// 标记滚动是否暂停
const isScrollingPaused = ref(false)
// 记录拼接数据时的滚动位置
let spliceScrollTop = 0
// 记录原始数据长度
const originalDataLength = ref(null)
// 滚动定时器
let scrollInterval
// 自动滚动
const startAutoScroll = () => {
scrollInterval = setInterval(() => {
const container = scrollContainer.value
if (container && !isScrollingPaused.value) {
container.scrollTop += 1 //每次往上移动1个单位
// 检测是否滚动到底部
if (container.scrollTop + container.clientHeight >= container.scrollHeight) {
// 将原始数据拼接到当前显示数据后面
gissWarnInfoData.value = [...gissWarnInfoData.value, ...gissWarnInfoTotal.value]
// 记录拼接时的滚动位置
spliceScrollTop = container.scrollTop
}
//当原始的十条数据的最后一条数据滚动过可视区域时
if (container.scrollTop >= originalDataLength.value * getListItemHeight()) {
// 删除原来的十条数据
gissWarnInfoData.value = gissWarnInfoData.value.splice(0, originalDataLength.value)
// 调整滚动位置
container.scrollTop = container.scrollTop - originalDataLength.value * getListItemHeight()
}
}
}, 50) // 每 50ms 滚动一次
}
// 获取列表项的高度
const getListItemHeight = () => {
const container = scrollContainer.value
if (container && container.children.length > 0) {
return container.children[0].offsetHeight + 10
}
return 0
}
// 停止滚动
const stopAutoScroll = () => {
clearInterval(scrollInterval)
}
// 鼠标移入暂停滚动
const stopScrolling = () => {
isScrollingPaused.value = true
stopAutoScroll()
}
// 鼠标移出继续滚动
const startScrolling = () => {
isScrollingPaused.value = false
startAutoScroll()
}
调整位置是必须的哈~,大家可以参考一下,如果有更好的方法可以评论区交流~