vue实现奇偶行
Vue实现表格奇偶行样式
通过Vue动态绑定类名或样式,可以轻松实现表格奇偶行不同样式的效果。以下是几种常见实现方式:
方法一:使用v-bind:class动态绑定类名
<template>
<table>
<tr v-for="(item, index) in list" :key="item.id"
:class="{ 'even-row': index % 2 === 0, 'odd-row': index % 2 !== 0 }">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</template>
<style>
.even-row {
background-color: #f8f8f8;
}
.odd-row {
background-color: #ffffff;
}
</style>
方法二:使用计算属性生成样式数组
<template>
<table>
<tr v-for="(item, index) in list" :key="item.id"
:style="getRowStyle(index)">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</template>
<script>
export default {
methods: {
getRowStyle(index) {
return {
backgroundColor: index % 2 === 0 ? '#f8f8f8' : '#ffffff'
}
}
}
}
</script>
方法三:使用CSS nth-child选择器(纯CSS方案)
<template>
<table class="stripe-table">
<tr v-for="item in list" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</template>
<style>
.stripe-table tr:nth-child(even) {
background-color: #f8f8f8;
}
.stripe-table tr:nth-child(odd) {
background-color: #ffffff;
}
</style>
方法四:使用Vue渲染函数

export default {
render(h) {
return h('table',
this.list.map((item, index) => {
return h('tr', {
class: {
'even-row': index % 2 === 0,
'odd-row': index % 2 !== 0
}
}, [
h('td', item.name),
h('td', item.value)
])
})
)
}
}
注意事项
- 动态绑定类名方式适用于需要频繁切换样式的场景
- CSS选择器方式性能最优,但不支持动态修改样式
- 计算属性方式适合需要复杂逻辑判断的情况
- 在大型表格中,考虑使用虚拟滚动优化性能






