使用v-for实现点击当前li,li背景颜色变为红色,其余颜色不变

在 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 属性来确保这些样式只应用于当前组件。

相关推荐

  1. el-table每一行加背景颜色

    2024-06-12 14:18:04       30 阅读
  2. 菜单改变svg图标颜色

    2024-06-12 14:18:04       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-12 14:18:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-12 14:18:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-12 14:18:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-12 14:18:04       18 阅读

热门阅读

  1. Web前端魂斗罗:深度剖析前端技术的奇幻之旅

    2024-06-12 14:18:04       6 阅读
  2. 第5天:Flask应用结构

    2024-06-12 14:18:04       6 阅读
  3. 记录 unplugin-vue-components不生效

    2024-06-12 14:18:04       7 阅读
  4. 【持久层】PostgreSQL使用教程

    2024-06-12 14:18:04       11 阅读
  5. Springboot配置websocket,https使用 WebSocket 连接

    2024-06-12 14:18:04       9 阅读
  6. React组件通信方式总结

    2024-06-12 14:18:04       5 阅读
  7. 原生js实现缩略图

    2024-06-12 14:18:04       4 阅读
  8. perf kvm to profile vm_exit

    2024-06-12 14:18:04       12 阅读
  9. unordered_set,unordered_map模拟实现

    2024-06-12 14:18:04       6 阅读
  10. Web前端入门必学:解锁数字世界的魔法钥匙

    2024-06-12 14:18:04       6 阅读
  11. PHP 文件上传:全面指南与最佳实践

    2024-06-12 14:18:04       8 阅读
  12. linux top 中显示swap用量并排序

    2024-06-12 14:18:04       8 阅读