vue实现表格样式
Vue 实现表格样式的方法
使用原生 HTML 表格
通过 Vue 的模板语法直接渲染 HTML 表格,结合 CSS 控制样式。
<template>
<table class="custom-table">
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.id">
<td v-for="cell in row.cells" :key="cell">{{ cell }}</td>
</tr>
</tbody>
</table>
</template>
<style scoped>
.custom-table {
width: 100%;
border-collapse: collapse;
}
.custom-table th, .custom-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.custom-table th {
background-color: #f2f2f2;
}
.custom-table tr:nth-child(even) {
background-color: #f9f9f9;
}
.custom-table tr:hover {
background-color: #e9e9e9;
}
</style>
使用 Element UI 表格组件
Element UI 提供了丰富的表格组件和样式配置。

<template>
<el-table :data="tableData" style="width: 100%" stripe border>
<el-table-column prop="date" label="日期" width="180"></el-table-column>
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ date: '2023-01-01', name: '张三', address: '北京市' },
{ date: '2023-01-02', name: '李四', address: '上海市' }
]
}
}
}
</script>
使用 Vuetify 表格组件
Vuetify 提供了 Material Design 风格的表格组件。

<template>
<v-data-table
:headers="headers"
:items="items"
:items-per-page="5"
class="elevation-1"
></v-data-table>
</template>
<script>
export default {
data() {
return {
headers: [
{ text: '姓名', value: 'name' },
{ text: '年龄', value: 'age' }
],
items: [
{ name: '张三', age: 25 },
{ name: '李四', age: 30 }
]
}
}
}
</script>
动态样式绑定
通过 Vue 的动态样式绑定实现条件样式。
<template>
<table>
<tr v-for="row in rows" :key="row.id" :class="{ 'highlight-row': row.highlight }">
<td>{{ row.content }}</td>
</tr>
</table>
</template>
<style>
.highlight-row {
background-color: yellow;
}
</style>
使用 CSS 框架
结合 Bootstrap 等 CSS 框架快速实现表格样式。
<template>
<table class="table table-striped table-hover">
<tr v-for="row in rows" :key="row.id">
<td>{{ row.content }}</td>
</tr>
</table>
</template>
这些方法可以根据项目需求灵活选择,原生表格适合简单需求,UI 框架适合快速开发,动态样式绑定适合复杂交互场景。






