vue实现跑道滚动
vue实现跑道滚动效果
跑道滚动效果常见于轮播图或横向滚动展示场景,以下是几种实现方法:
使用CSS动画实现基础滚动
<template>
<div class="track-container">
<div class="track" :style="{ animationDuration: duration + 's' }">
<div v-for="(item, index) in items" :key="index" class="item">
{{ item }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [1, 2, 3, 4, 5],
duration: 10
}
}
}
</script>
<style scoped>
.track-container {
overflow: hidden;
width: 100%;
}
.track {
display: flex;
animation: scroll linear infinite;
}
@keyframes scroll {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-100%);
}
}
.item {
flex-shrink: 0;
width: 200px;
height: 100px;
margin-right: 20px;
background: #eee;
display: flex;
align-items: center;
justify-content: center;
}
</style>
使用requestAnimationFrame实现高性能滚动

export default {
data() {
return {
items: [1, 2, 3, 4, 5],
position: 0,
speed: 1,
animationId: null
}
},
mounted() {
this.startAnimation()
},
beforeDestroy() {
cancelAnimationFrame(this.animationId)
},
methods: {
startAnimation() {
const animate = () => {
this.position -= this.speed
if (Math.abs(this.position) >= this.$refs.track.scrollWidth / 2) {
this.position = 0
}
this.$refs.track.style.transform = `translateX(${this.position}px)`
this.animationId = requestAnimationFrame(animate)
}
animate()
}
}
}
无限循环滚动的优化版本
<template>
<div class="track-wrapper">
<div class="track" ref="track">
<div v-for="item in displayItems" :key="item.id" class="item">
{{ item.content }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
{ id: 3, content: 'Item 3' }
],
displayItems: []
}
},
mounted() {
this.duplicateItems()
this.startScroll()
},
methods: {
duplicateItems() {
this.displayItems = [...this.items, ...this.items]
},
startScroll() {
// 实现滚动逻辑
}
}
}
</script>
使用第三方库实现

可以考虑使用swiper.js等成熟轮播库:
import Swiper from 'swiper'
import 'swiper/css/swiper.css'
export default {
mounted() {
new Swiper('.swiper-container', {
loop: true,
autoplay: {
delay: 2500,
disableOnInteraction: false
},
slidesPerView: 'auto',
spaceBetween: 30
})
}
}
响应式处理
添加窗口大小变化的响应处理:
export default {
data() {
return {
itemWidth: 200
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
this.handleResize()
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.itemWidth = window.innerWidth > 768 ? 200 : 150
}
}
}
以上方法可以根据实际需求选择,CSS动画适合简单场景,requestAnimationFrame提供更精细控制,第三方库则提供开箱即用的完整解决方案。






