如何在Vue中每3秒循环切换元素的active类?
Vue实现每3秒循环切换区块的active类
实现思路
通过维护响应式的当前激活索引,结合定时器定时更新索引,利用Vue的类绑定语法动态切换active类,实现循环切换效果。
完整代码示例
模板部分
<template> <div class="box-container"> <div v-for="(item, index) in items" :key="index" class="box-item" :class="{ active: index === currentIndex }" > {{ item }} </div> </div> </template>
脚本部分
<script setup> import { ref, onMounted, onBeforeUnmount } from 'vue' // 模拟区块数据,可根据实际需求替换 const items = ref(['区块1', '区块2', '区块3']) const currentIndex = ref(0) let timer = null onMounted(() => { // 启动定时器,每3秒更新激活索引 timer = setInterval(() => { currentIndex.value = (currentIndex.value + 1) % items.value.length }, 3000) }) onBeforeUnmount(() => { // 组件卸载前清除定时器,避免内存泄漏 clearInterval(timer) }) </script>
样式部分
<style scoped> .box-item { width: 100px; height: 100px; margin: 10px; background: #eee; display: inline-flex; align-items: center; justify-content: center; transition: background 0.3s; } .box-item.active { background: #42b983; color: white; } </style>
关键说明
- 响应式索引:
currentIndex跟踪当前激活的区块索引,Vue会自动响应其变化更新DOM类名。 - 循环逻辑:通过
(currentIndex + 1) % items.length实现索引循环,当索引到达最后一项后自动重置为0。 - 定时器清理:组件卸载时调用
clearInterval清除定时器,避免内存泄漏。 - 类绑定:使用
:class="{ active: index === currentIndex }"实现条件性添加active类。
内容的提问来源于stack exchange,提问作者Дмитрий Моисеев
相关产品推荐
相关产品推荐

