vue实现字体垂直轮播
Vue 实现字体垂直轮播的方法
垂直轮播效果通常用于展示公告、新闻标题等。以下是几种实现方式:
使用 CSS 动画实现
通过 Vue 控制 CSS 动画实现简单的垂直轮播效果:
<template>
<div class="vertical-carousel">
<div class="carousel-list" :style="{ transform: `translateY(${translateY}px)` }">
<div v-for="(item, index) in items" :key="index" class="carousel-item">
{{ item }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['公告1', '公告2', '公告3', '公告4'],
currentIndex: 0,
translateY: 0,
itemHeight: 40 // 根据实际项目高度调整
}
},
mounted() {
this.startCarousel()
},
methods: {
startCarousel() {
setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.items.length
this.translateY = -this.currentIndex * this.itemHeight
}, 2000)
}
}
}
</script>
<style>
.vertical-carousel {
height: 40px;
overflow: hidden;
position: relative;
}
.carousel-list {
transition: transform 0.5s ease;
}
.carousel-item {
height: 40px;
line-height: 40px;
}
</style>
使用第三方库
对于更复杂的需求,可以使用 vue-awesome-swiper 等轮播库:

-
安装依赖:
npm install swiper vue-awesome-swiper --save -
实现代码:

<template> <swiper :options="swiperOption" direction="vertical" class="vertical-swiper"> <swiper-slide v-for="(item, index) in items" :key="index"> {{ item }} </swiper-slide> </swiper> </template>
export default { components: { Swiper, SwiperSlide }, data() { return { items: ['消息1', '消息2', '消息3', '消息4'], swiperOption: { direction: 'vertical', autoplay: { delay: 2000, disableOnInteraction: false }, loop: true, slidesPerView: 1, spaceBetween: 0 } } } }
.vertical-swiper { height: 40px; } ```无限循环无缝轮播
实现无缝轮播效果,避免跳转时的突兀感:
<template>
<div class="seamless-carousel" ref="carousel">
<div class="carousel-content">
<div v-for="(item, index) in extendedItems"
:key="index"
class="carousel-item"
:class="{ active: index === currentIndex }">
{{ item }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['新闻1', '新闻2', '新闻3'],
currentIndex: 0,
extendedItems: []
}
},
created() {
this.extendedItems = [...this.items, this.items[0]]
},
mounted() {
this.startCarousel()
},
methods: {
startCarousel() {
setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.extendedItems.length
if (this.currentIndex === this.items.length) {
setTimeout(() => {
this.currentIndex = 0
}, 500)
}
}, 2000)
}
}
}
</script>
<style>
.seamless-carousel {
height: 40px;
overflow: hidden;
position: relative;
}
.carousel-content {
transition: transform 0.5s ease;
}
.carousel-item {
height: 40px;
line-height: 40px;
}
</style>
注意事项
- 轮播高度需要根据实际内容调整
- 移动端需要考虑触摸事件处理
- 性能优化:组件销毁时清除定时器
- 内容更新时需要重置轮播状态
- 对于大量数据考虑虚拟滚动技术
以上方法可以根据实际需求进行调整和组合,实现更复杂的垂直轮播效果。






