vue实现新闻滚动
Vue 实现新闻滚动效果
新闻滚动效果通常用于展示动态更新的新闻标题或内容,可以通过多种方式实现。以下是几种常见的实现方法:
使用 CSS 动画实现基础滚动
通过 CSS 的 animation 和 @keyframes 实现简单的横向或纵向滚动效果。
<template>
<div class="news-scroll-container">
<div class="news-scroll-content">
{{ newsContent }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
newsContent: "这里是滚动新闻内容,可以是动态更新的数据..."
};
}
};
</script>
<style>
.news-scroll-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.news-scroll-content {
display: inline-block;
animation: scroll 10s linear infinite;
}
@keyframes scroll {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
使用 Vue 动态数据绑定实现无缝滚动
通过动态更新数据实现无缝滚动效果,适用于需要从后端获取新闻数据的场景。

<template>
<div class="news-scroll-container">
<div
class="news-scroll-content"
:style="{ transform: `translateX(${scrollPosition}px)` }"
>
<span v-for="(item, index) in newsList" :key="index">
{{ item.title }}
</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
newsList: [
{ title: "新闻标题1" },
{ title: "新闻标题2" },
{ title: "新闻标题3" }
],
scrollPosition: 0,
scrollInterval: null
};
},
mounted() {
this.startScrolling();
},
beforeDestroy() {
this.stopScrolling();
},
methods: {
startScrolling() {
this.scrollInterval = setInterval(() => {
this.scrollPosition -= 1;
if (this.scrollPosition < -300) {
this.scrollPosition = 0;
}
}, 30);
},
stopScrolling() {
clearInterval(this.scrollInterval);
}
}
};
</script>
<style>
.news-scroll-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.news-scroll-content {
display: inline-block;
}
</style>
使用第三方库实现复杂滚动效果
对于更复杂的滚动需求,可以使用第三方库如 vue-marquee 或 vue-awesome-marquee。
安装 vue-marquee:

npm install vue-marquee-text-component
使用示例:
<template>
<marquee-text :duration="20" :repeat="5">
<span v-for="(item, index) in newsList" :key="index">
{{ item.title }}
</span>
</marquee-text>
</template>
<script>
import MarqueeText from 'vue-marquee-text-component';
export default {
components: {
MarqueeText
},
data() {
return {
newsList: [
{ title: "新闻标题1" },
{ title: "新闻标题2" },
{ title: "新闻标题3" }
]
};
}
};
</script>
垂直滚动实现方法
如果需要垂直滚动效果,可以调整 CSS 或使用专门的垂直滚动组件。
<template>
<div class="vertical-scroll-container">
<div class="vertical-scroll-content">
<div v-for="(item, index) in newsList" :key="index" class="news-item">
{{ item.title }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
newsList: [
{ title: "新闻标题1" },
{ title: "新闻标题2" },
{ title: "新闻标题3" }
]
};
}
};
</script>
<style>
.vertical-scroll-container {
height: 100px;
overflow: hidden;
}
.vertical-scroll-content {
animation: vertical-scroll 10s linear infinite;
}
@keyframes vertical-scroll {
0% { transform: translateY(0); }
100% { transform: translateY(-100%); }
}
.news-item {
height: 30px;
line-height: 30px;
}
</style>
以上方法可以根据实际需求进行调整,如滚动速度、方向、暂停交互等功能的添加。






