vue3 无缝列表循环
vue3的无缝列表循环播放
自动轮播 鼠标悬停可以停止滚动
<template><div><div class="title">今日实时问题治理</div><div@mouseenter="handleMouseEnter"@mouseleave="handleMouseLeave"class="main_container"><divref="scrollContainer"class="scroll_container"><divv-for="item in extendedListData":key="item.id"class="scroll_item"><span>{{ item.time }}</span><span>{{ item.name }}</span><span>{{ item.type }}</span><span>{{ item.desc }}</span><div :class="item.status === 1 ? 'low' : 'high'">{{ item.status === 1 ? '低风险' : '一般风险' }}</div><span>{{ item.state }}</span></div></div></div></div>
</template><script setup>
import {reactive,ref,onMounted,onBeforeUnmount,onUnmounted,nextTick
} from "vue"let listData = reactive([{time: "14:30",name: "车间1",type: "作业活动",desc: "保险装置未过关",status: 2,state: "已完成"},{time: "14:40",name: "车间2",type: "作业活动",desc: "保险装置未过关",status: 1,state: "已完成"},{time: "14:50",name: "车间3",type: "作业活动",desc: "保险装置未过关",status: 2,state: "已完成"},{time: "15:00",name: "车间4",type: "作业活动",desc: "保险装置未过关",status: 2,state: "已完成"},{time: "16:40",name: "车间5",type: "作业活动",desc: "保险装置未过关",status: 1,state: "已完成"},{time: "17:20",name: "车间6",type: "作业活动",desc: "保险装置未过关",status: 2,state: "已完成"}
])
let timer = ref(null)
let scrollContainer = ref(null)
// 创建双倍数据集以实现无缝滚动
const extendedListData = reactive([...listData, ...listData])onBeforeUnmount(() => {clearInterval(timer.value)
})onUnmounted(() => {clearInterval(timer.value)
})function handleMouseEnter() {clearInterval(timer.value)
}function handleMouseLeave() {start()
}function start() {clearInterval(timer.value)let speed = 25timer.value = setInterval(ListScroll, speed)
}function ListScroll() {let scrollDom = scrollContainer.valueif (scrollDom.offsetHeight === 0) {scrollDom = scrollDom = scrollContainer.value} else {if (scrollDom.children.length < 4) {clearInterval(timer.value)return}scrollDom.scrollTop += 1if (scrollDom.scrollTop >=scrollDom.scrollHeight - scrollDom.clientHeight) {// 滚动到末尾时,重置滚动位置并重新放置第一个元素scrollDom.scrollTop = 0const first = scrollDom.children[0]scrollDom.removeChild(first)scrollDom.appendChild(first)}}
}// 初始化时启动滚动
onMounted(() => {nextTick(() => {start()})
})
</script>
<style lang="scss" scoped>
.title {color: #fff;text-align: center;background-color: rgba(18, 51, 95, 0.9);font-size: 16px;padding: 8px 0;font-weight: 700;
}.main_container {height: 300px;padding: 20px;.scroll_container {color: #fff;width: 100%;height: 100%;overflow: hidden;.scroll_item {padding: 0 16px;display: flex;align-items: center;justify-content: space-between;height: 48px;margin-bottom: 10px;div {width: 72px;text-align: center;color: #ffffff;border-radius: 4px;margin-right: 8px;height: 30px;line-height: 30px;}.low {background: #3471ff;}.high {background: #ffca19;}}.scroll_item:nth-child(odd) {background-color: rgba(255, 255, 255, 0.3);color: white;}}
}
</style>