vue实现轮播文字
Vue 实现轮播文字
使用 CSS 动画实现
通过 CSS 的 @keyframes 和 animation 属性实现文字轮播效果。定义一个动画,让文字从一侧移动到另一侧。
<template>
<div class="text-carousel">
<div class="text-content">{{ currentText }}</div>
</div>
</template>
<script>
export default {
data() {
return {
texts: ["文本1", "文本2", "文本3", "文本4"],
currentIndex: 0,
};
},
computed: {
currentText() {
return this.texts[this.currentIndex];
},
},
mounted() {
setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.texts.length;
}, 2000);
},
};
</script>
<style>
.text-carousel {
overflow: hidden;
white-space: nowrap;
width: 100%;
}
.text-content {
display: inline-block;
animation: slide 10s linear infinite;
}
@keyframes slide {
0% {
transform: translateX(100%);
}
100% {
transform: translateX(-100%);
}
}
</style>
使用 Vue Transition 组件
通过 Vue 的 <transition> 组件实现文字淡入淡出效果。结合 v-for 和 v-if 动态切换显示的文字。
<template>
<div class="text-carousel">
<transition name="fade" mode="out-in">
<div :key="currentText">{{ currentText }}</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
texts: ["文本1", "文本2", "文本3", "文本4"],
currentIndex: 0,
};
},
computed: {
currentText() {
return this.texts[this.currentIndex];
},
},
mounted() {
setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.texts.length;
}, 2000);
},
};
</script>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
</style>
使用第三方库(如 vue-awesome-swiper)
如果需要更复杂的效果(如触摸滑动、分页器等),可以使用 vue-awesome-swiper 库。
安装依赖:
npm install swiper vue-awesome-swiper
代码示例:
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(text, index) in texts" :key="index">
{{ text }}
</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from "vue-awesome-swiper";
import "swiper/css/swiper.css";
export default {
components: {
Swiper,
SwiperSlide,
},
data() {
return {
texts: ["文本1", "文本2", "文本3", "文本4"],
swiperOptions: {
autoplay: {
delay: 2000,
},
loop: true,
},
};
},
};
</script>
注意事项
- 动画性能优化:避免频繁触发重排和重绘,使用
transform和opacity属性。 - 响应式设计:确保轮播容器在不同屏幕尺寸下正常显示。
- 内存管理:在组件销毁时清除定时器,避免内存泄漏。







