vue实现新闻滚动
Vue实现新闻滚动效果
新闻滚动是常见的网页动态效果,可通过Vue结合CSS动画或第三方库实现。以下是几种常见方法:
方法一:使用CSS动画和v-for
定义数据数组并通过CSS实现无限滚动动画:
<template>
<div class="news-container">
<div class="news-list" :style="{ transform: `translateY(${scrollPosition}px)` }">
<div v-for="(item, index) in newsData" :key="index" class="news-item">
{{ item.title }}
</div>
<!-- 复制首条数据实现无缝衔接 -->
<div v-for="(item, index) in newsData" :key="'copy'+index" class="news-item">
{{ item.title }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
newsData: [
{ title: "新闻标题1" },
{ title: "新闻标题2" },
{ title: "新闻标题3" }
],
scrollPosition: 0
}
},
mounted() {
setInterval(() => {
this.scrollPosition -= 1;
if (-this.scrollPosition >= document.querySelector('.news-item').offsetHeight * this.newsData.length) {
this.scrollPosition = 0;
}
}, 50);
}
}
</script>
<style>
.news-container {
height: 200px;
overflow: hidden;
position: relative;
}
.news-list {
position: absolute;
transition: transform 0.5s linear;
}
.news-item {
height: 40px;
line-height: 40px;
border-bottom: 1px solid #eee;
}
</style>
方法二:使用vue-seamless-scroll插件
安装插件后快速实现无缝滚动:
npm install vue-seamless-scroll
组件实现:
<template>
<vue-seamless-scroll
:data="newsData"
:class-option="options"
class="seamless-wrap"
>
<ul>
<li v-for="(item, index) in newsData" :key="index">
{{ item.title }}
</li>
</ul>
</vue-seamless-scroll>
</template>
<script>
import vueSeamlessScroll from 'vue-seamless-scroll'
export default {
components: { vueSeamlessScroll },
data() {
return {
newsData: [
{ title: "动态新闻1" },
{ title: "动态新闻2" },
{ title: "动态新闻3" }
]
}
},
computed: {
options() {
return {
step: 0.5, // 滚动步长
limitMoveNum: 3, // 开始滚动的数据量
hoverStop: true, // 悬停暂停
direction: 1, // 0向下 1向上 2向左 3向右
openWatch: true // 开启数据实时监控
}
}
}
}
</script>
<style>
.seamless-wrap {
height: 200px;
overflow: hidden;
}
</style>
方法三:Marquee标签替代方案(兼容方案)
虽然HTML5已废弃marquee标签,但仍可通过CSS模拟:
<template>
<div class="marquee">
<div class="track" :style="{ transform: `translateX(${position}px)` }">
<span v-for="(item, index) in newsData" :key="index">
{{ item.title }}
</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
newsData: [...],
position: 0,
timer: null
}
},
mounted() {
this.startScroll()
},
methods: {
startScroll() {
this.timer = setInterval(() => {
this.position -= 1
if (-this.position > this.$el.querySelector('.track').scrollWidth / 2) {
this.position = 0
}
}, 20)
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style>
.marquee {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.track {
display: inline-block;
transition: transform 0.2s linear;
}
</style>
注意事项
- 移动端需考虑touch事件处理
- 大量数据时建议使用虚拟滚动技术
- 暂停逻辑可绑定mouseenter/mouseleave事件
- 动态更新数据时需要重置滚动位置







