在 Vue 3 的 <script setup>
语法中,可以使用 ref
或 reactive
来追踪和管理 DOM 元素的引用。然后,你可以使用事件监听器(如 @click
)来响应点击事件,并为当前点击的 <li>
元素添加 active
类名。
<template> <ul> <li v-for="(item, index) in items" :key="index" :class="{ active: currentIndex === index }" @click="setCurrentIndex(index)"> {{ item }} </li> </ul>
</template> <script setup>
import { ref } from 'vue'; const items = [ '全部', '节日祝福', '科普服务', // ... 其他项目 '种草带货', '知识口播', '热点资讯'
]; const currentIndex = ref(0); // 默认激活第一个项目 function setCurrentIndex(index) { currentIndex.value = index;
}
</script> <style scoped>
.active { /* 这里定义active类的样式 */ background-color: #f44336; color: white;
}
</style>
在这个例子中,定义了一个 items
数组来存储所有的列表项,以及一个 currentIndex
的 ref
来追踪当前激活的列表项的索引。使用 v-for
指令来遍历 items
数组,并为每个 <li>
元素添加一个点击事件监听器 @click
,它调用 setCurrentIndex
方法来更新 currentIndex
的值。
:class="{ active: currentIndex === index }"
是一个对象语法,用于动态绑定类名。当 currentIndex
等于当前循环的 index
时,active
类就会被添加到对应的 <li>
元素上。
在 <style>
标签中,定义了 .active
类的样式,你可以根据需要自定义这个样式。
这样,当你点击任何一个 <li>
元素时,它都会获得 active
类名,并且之前的 active
类名会被移除。