vue实现简单表格
Vue 实现简单表格的方法
使用原生 HTML 表格结构
在 Vue 模板中直接使用 <table> 标签构建基础表格结构,通过 v-for 动态渲染数据:
<template>
<table class="simple-table">
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in tableData" :key="index">
<td v-for="(value, key) in row" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职业'],
tableData: [
{ 姓名: '张三', 年龄: 25, 职业: '工程师' },
{ 姓名: '李四', 年龄: 30, 职业: '设计师' }
]
}
}
}
</script>
<style scoped>
.simple-table {
border-collapse: collapse;
width: 100%;
}
.simple-table th, .simple-table td {
border: 1px solid #ddd;
padding: 8px;
}
.simple-table th {
background-color: #f2f2f2;
}
</style>
使用第三方组件库
对于更复杂的需求,可以集成现成的表格组件库:
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
<el-table-column prop="job" label="职业"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 25, job: '工程师' },
{ name: '李四', age: 30, job: '设计师' }
]
}
}
}
</script>
动态表格实现
通过计算属性实现动态列渲染和数据处理:
<template>
<table>
<thead>
<tr>
<th v-for="col in computedColumns" :key="col.field">
{{ col.title }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="item in processedData" :key="item.id">
<td v-for="col in computedColumns" :key="col.field">
{{ item[col.field] }}
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
props: ['rawData'],
computed: {
computedColumns() {
return [
{ field: 'name', title: '姓名' },
{ field: 'value', title: '数值' }
]
},
processedData() {
return this.rawData.map(item => ({
...item,
value: item.value * 2 // 示例数据处理
}))
}
}
}
</script>
表格交互功能实现
添加排序、筛选等交互功能:
<template>
<table>
<thead>
<tr>
<th @click="sortBy('name')">姓名</th>
<th @click="sortBy('age')">年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="item in sortedData" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 }
],
sortKey: '',
sortOrder: 1
}
},
computed: {
sortedData() {
return [...this.tableData].sort((a, b) => {
return a[this.sortKey] > b[this.sortKey] ? this.sortOrder : -this.sortOrder
})
}
},
methods: {
sortBy(key) {
this.sortOrder = this.sortKey === key ? -this.sortOrder : 1
this.sortKey = key
}
}
}
</script>
响应式表格设计
通过 CSS 实现响应式表格布局:

@media screen and (max-width: 600px) {
table {
border: 0;
}
table thead {
display: none;
}
table tr {
display: block;
margin-bottom: 1rem;
border: 1px solid #ddd;
}
table td {
display: block;
text-align: right;
border-bottom: 1px solid #eee;
}
table td::before {
content: attr(data-label);
float: left;
font-weight: bold;
}
}






