vue实现表格输出
Vue 实现表格输出的方法
使用原生表格标签
在 Vue 模板中可以直接使用 HTML 原生表格标签(<table>、<tr>、<td>等)渲染数据。通过 v-for 指令循环数据生成表格行。
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 25 },
{ name: '李四', age: 30 }
]
}
}
}
</script>
使用第三方表格组件
流行的 Vue 表格组件库包括 Element UI、Ant Design Vue 等,提供更丰富的功能(排序、分页、筛选等)。
以 Element UI 为例:
<template>
<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 25 },
{ name: '李四', age: 30 }
]
}
}
}
</script>
动态生成表格列
当列需要动态配置时,可以通过 v-for 循环生成列:
<template>
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col.prop">{{ col.label }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td v-for="col in columns" :key="col.prop">{{ item[col.prop] }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
columns: [
{ prop: 'name', label: '姓名' },
{ prop: 'age', label: '年龄' }
],
tableData: [
{ name: '张三', age: 25 },
{ name: '李四', age: 30 }
]
}
}
}
</script>
添加交互功能
通过 Vue 方法实现表格的常见交互:
<template>
<table>
<thead>
<tr>
<th v-for="col in columns" :key="col.prop" @click="sortTable(col.prop)">
{{ col.label }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in sortedData" :key="index">
<td v-for="col in columns" :key="col.prop">{{ item[col.prop] }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
columns: [
{ prop: 'name', label: '姓名' },
{ prop: 'age', label: '年龄' }
],
tableData: [
{ name: '张三', age: 25 },
{ name: '李四', age: 30 }
],
sortKey: '',
sortOrder: 1
}
},
computed: {
sortedData() {
if (!this.sortKey) return this.tableData
return [...this.tableData].sort((a, b) => {
return (a[this.sortKey] > b[this.sortKey] ? 1 : -1) * this.sortOrder
})
}
},
methods: {
sortTable(key) {
this.sortOrder = this.sortKey === key ? -this.sortOrder : 1
this.sortKey = key
}
}
}
</script>
响应式表格设计
使用 CSS 实现表格在不同屏幕尺寸下的响应式布局:
@media screen and (max-width: 600px) {
table {
display: block;
}
thead {
display: none;
}
tr {
display: block;
margin-bottom: 1rem;
border: 1px solid #ddd;
}
td {
display: block;
text-align: right;
padding-left: 50%;
position: relative;
}
td::before {
content: attr(data-label);
position: absolute;
left: 0;
width: 50%;
padding-left: 1rem;
text-align: left;
font-weight: bold;
}
}
需要为 td 添加 data-label 属性:
<td v-for="col in columns" :key="col.prop" :data-label="col.label">
{{ item[col.prop] }}
</td>






