vue实现关键词轮播
Vue 实现关键词轮播的方法
使用 Vue 的 v-for 和定时器
创建一个数据数组存储关键词,使用 v-for 渲染到页面。通过 setInterval 定时更新当前显示的关键词索引。
<template>
<div>
<div v-for="(keyword, index) in keywords" :key="index" v-show="currentIndex === index">
{{ keyword }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
keywords: ['Vue', 'React', 'Angular', 'Svelte'],
currentIndex: 0,
interval: null
}
},
mounted() {
this.interval = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.keywords.length
}, 2000)
},
beforeDestroy() {
clearInterval(this.interval)
}
}
</script>
使用 CSS 动画效果
结合 CSS 过渡效果,让关键词切换更平滑。通过动态绑定 class 实现淡入淡出效果。
<template>
<div class="keyword-slider">
<div
v-for="(keyword, index) in keywords"
:key="index"
:class="{ 'active': currentIndex === index }"
>
{{ keyword }}
</div>
</div>
</template>
<style>
.keyword-slider div {
opacity: 0;
transition: opacity 0.5s ease;
position: absolute;
}
.keyword-slider div.active {
opacity: 1;
}
</style>
使用第三方轮播组件
集成成熟的轮播库如 vue-awesome-swiper,可以快速实现更复杂的效果。
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(keyword, index) in keywords" :key="index">
{{ keyword }}
</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/swiper-bundle.css'
export default {
components: { Swiper, SwiperSlide },
data() {
return {
keywords: ['Vue', 'React', 'Angular'],
swiperOptions: {
autoplay: {
delay: 2000
},
loop: true
}
}
}
}
</script>
响应式关键词轮播
根据屏幕尺寸调整轮播速度和样式,通过监听 resize 事件动态改变参数。

<template>
<div :style="{ fontSize: fontSize + 'px' }">
{{ currentKeyword }}
</div>
</template>
<script>
export default {
data() {
return {
keywords: ['响应式', '自适应', '移动优先'],
currentIndex: 0,
fontSize: 16
}
},
created() {
window.addEventListener('resize', this.handleResize)
this.handleResize()
},
methods: {
handleResize() {
this.fontSize = window.innerWidth < 768 ? 14 : 18
}
}
}
</script>
每种方法适用于不同场景,从简单实现到复杂效果均可覆盖。根据项目需求选择合适方案,注意在组件销毁时清除定时器避免内存泄漏。






