vue 实现数据滚动
Vue 实现数据滚动的方法
使用 CSS 动画实现滚动
通过 CSS 的 animation 和 @keyframes 实现滚动效果。适用于简单的文字或列表滚动。
<template>
<div class="scroll-container">
<div class="scroll-content">
{{ scrollingText }}
</div>
</div>
</template>
<style>
.scroll-container {
overflow: hidden;
white-space: nowrap;
}
.scroll-content {
display: inline-block;
animation: scroll 10s linear infinite;
}
@keyframes scroll {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
使用 Vue 的 v-for 和定时器动态更新数据
适用于动态加载的数据列表滚动,通过定时器控制数据的更新。
<template>
<div class="list-container">
<div v-for="(item, index) in items" :key="index">
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4'],
};
},
mounted() {
setInterval(() => {
this.items.push(this.items.shift());
}, 1000);
},
};
</script>
使用第三方库(如 vue-seamless-scroll)
对于更复杂的滚动需求,可以使用专门为 Vue 设计的滚动库。
安装库:
npm install vue-seamless-scroll
使用示例:
<template>
<vue-seamless-scroll :data="listData" class="scroll-wrap">
<ul>
<li v-for="(item, index) in listData" :key="index">
{{ item }}
</li>
</ul>
</vue-seamless-scroll>
</template>
<script>
import vueSeamlessScroll from 'vue-seamless-scroll';
export default {
components: { vueSeamlessScroll },
data() {
return {
listData: ['Item 1', 'Item 2', 'Item 3', 'Item 4'],
};
},
};
</script>
使用 CSS marquee 标签(不推荐)
虽然 marquee 标签可以实现滚动效果,但它是过时的 HTML 标签,不建议在生产环境中使用。

<template>
<marquee behavior="scroll" direction="left">
{{ scrollingText }}
</marquee>
</template>
注意事项
- 使用 CSS 动画时需注意性能问题,尤其是在移动设备上。
- 动态数据滚动时,确保定时器在组件销毁时清除,避免内存泄漏。
- 第三方库通常提供更多配置选项,如滚动速度、方向等,适合复杂场景。






