vue实现隔行选中
Vue 实现隔行选中功能
使用 v-for 和 :class 动态绑定样式
通过 v-for 循环渲染列表时,利用索引值判断奇偶行,动态绑定不同的样式类。例如:
<template>
<ul>
<li
v-for="(item, index) in list"
:key="item.id"
:class="{ 'even-row': index % 2 === 0, 'odd-row': index % 2 !== 0 }"
@click="selectRow(index)"
>
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
],
selectedIndex: null
}
},
methods: {
selectRow(index) {
this.selectedIndex = index
}
}
}
</script>
<style>
.even-row {
background-color: #f0f0f0;
}
.odd-row {
background-color: #ffffff;
}
.even-row.selected, .odd-row.selected {
background-color: #d4edff;
}
</style>
通过计算属性判断选中状态
使用计算属性动态生成样式类,结合点击事件切换选中状态:
<template>
<ul>
<li
v-for="(item, index) in list"
:key="item.id"
:class="rowClass(index)"
@click="toggleSelect(index)"
>
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
list: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
],
selectedIndices: []
}
},
methods: {
toggleSelect(index) {
const idx = this.selectedIndices.indexOf(index)
if (idx >= 0) {
this.selectedIndices.splice(idx, 1)
} else {
this.selectedIndices.push(index)
}
}
},
computed: {
rowClass() {
return (index) => ({
'even-row': index % 2 === 0,
'odd-row': index % 2 !== 0,
'selected': this.selectedIndices.includes(index)
})
}
}
}
</script>
使用第三方库实现复杂选择逻辑
对于更复杂的选择需求(如多选、范围选择等),可以考虑使用第三方表格组件库:

import { VDataTable } from 'vuetify/lib'
export default {
components: {
VDataTable
},
data() {
return {
headers: [
{ text: 'ID', value: 'id' },
{ text: 'Name', value: 'name' }
],
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
],
selected: []
}
}
}
<template>
<v-data-table
:headers="headers"
:items="items"
item-key="id"
show-select
v-model="selected"
class="elevation-1"
></v-data-table>
</template>






