当前位置:首页 > VUE

vue实现隔行选中

2026-03-29 10:28:17VUE

Vue 实现隔行选中

通过 v-for 循环渲染列表时,结合 :class 动态绑定样式实现隔行选中效果。

模板部分:

<template>
  <div>
    <ul>
      <li
        v-for="(item, index) in list"
        :key="item.id"
        @click="selectItem(index)"
        :class="{ 'selected': selectedIndex === index, 'even': index % 2 === 0 }"
      >
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

脚本部分:

<script>
export default {
  data() {
    return {
      list: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' },
        { id: 4, name: 'Item 4' }
      ],
      selectedIndex: null
    }
  },
  methods: {
    selectItem(index) {
      this.selectedIndex = index
    }
  }
}
</script>

样式部分:

vue实现隔行选中

<style scoped>
li {
  padding: 10px;
  cursor: pointer;
}

li.even {
  background-color: #f5f5f5;
}

li.selected {
  background-color: #42b983;
  color: white;
}
</style>

实现说明

  1. 数据绑定
    使用 v-for 循环渲染列表数据,index 参数表示当前项的索引。

  2. 隔行样式
    通过 index % 2 === 0 判断偶数行,动态绑定 even 类名实现隔行背景色。

    vue实现隔行选中

  3. 选中效果
    点击列表项时,将当前索引赋值给 selectedIndex,动态绑定 selected 类名高亮选中项。

扩展功能

多选支持
修改 selectedIndex 为数组类型,实现多选功能。

data() {
  return {
    selectedIndexes: []
  }
},
methods: {
  selectItem(index) {
    const idx = this.selectedIndexes.indexOf(index)
    if (idx === -1) {
      this.selectedIndexes.push(index)
    } else {
      this.selectedIndexes.splice(idx, 1)
    }
  }
}

样式调整
修改模板中的 :class 绑定,支持多选高亮。

:class="{ 'selected': selectedIndexes.includes(index), 'even': index % 2 === 0 }"

标签: vue
分享给朋友:

相关文章

vue实现博客

vue实现博客

Vue 实现博客的基本步骤 使用 Vue.js 实现一个博客系统可以分为前端和后端两部分。以下是基于 Vue 的前端实现方案,后端可以选择 Node.js、Django 或其他框架。 项目初始化 使…

vue实现开关

vue实现开关

Vue 实现开关组件的方法 使用原生HTML和Vue数据绑定 通过v-model绑定复选框的checked状态,结合CSS样式实现开关效果: <template> <label…

vue实现导入

vue实现导入

Vue 实现文件导入功能 使用 <input type="file"> 元素 在 Vue 模板中添加一个文件输入元素,绑定 change 事件处理函数。 <template>…

vue实现tabs

vue实现tabs

Vue实现Tabs组件的方法 使用动态组件和v-for指令 在Vue中创建Tabs组件可以通过动态组件和v-for指令实现。定义一个包含tab标题和内容的数组,使用v-for渲染tab标题,并通过点击…

vue实现hexo

vue实现hexo

Vue 集成 Hexo 的实现方法 Hexo 是一个静态博客框架,而 Vue 是一个前端框架。将 Vue 集成到 Hexo 中可以通过以下方式实现: 在 Hexo 中使用 Vue 组件 通过 Hex…

vue实现打印

vue实现打印

使用Vue实现打印功能 在Vue项目中实现打印功能可以通过多种方式完成,以下是几种常见的方法: 方法一:使用window.print() 这种方法适用于打印整个页面或特定区域的内容。 // 在Vu…