在 Vue 3 中,可以使用 <script setup>
语法糖来简化组件的编写。
下面是一个使用 Vue 3 和 <script setup>
实现的示例:
<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 = ref(['全部', '跨境', 'AI', '电商']);
const currentIndex = ref(null); // 用于记录当前激活的 li 的索引
// 设置当前索引的函数
function setCurrentIndex(index) {
currentIndex.value = index;
}
</script>
<style scoped>
li {
cursor: pointer; /* 添加鼠标悬停效果 */
}
li.active {
background-color: red; /* 激活状态的背景颜色 */
}
</style>
在这个示例中,定义了一个 items
的响应式引用(ref
)来保存所有的列表项,同时创建了一个 currentIndex
的响应式引用来保存当前被点击的列表项的索引。
在模板中,使用 v-for
指令来遍历 items
数组,并为每个列表项绑定一个点击事件处理器 setCurrentIndex
。当列表项被点击时,setCurrentIndex
函数会被调用,并传入当前列表项的索引。
除此之外还使用了一个对象字面量语法来绑定类名,:class="{ active: currentIndex === index }"
。当 currentIndex
的值等于当前列表项的索引时,active
类名会被添加到该列表项上,从而使其背景颜色变为红色。
最后,在 <style>
标签中定义了 .active
类的样式,使其背景颜色为红色。
注意,使用了 scoped
属性来确保这些样式只应用于当前组件。