vue实现简单表格
Vue 实现简单表格的方法
使用原生 HTML 表格结构
在 Vue 模板中直接使用 HTML 的 <table> 标签结构,结合 Vue 的指令动态渲染数据。
<template>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in rows" :key="index">
<td v-for="(value, key) in row" :key="key">{{ value }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '城市'],
rows: [
{ 姓名: '张三', 年龄: 25, 城市: '北京' },
{ 姓名: '李四', 年龄: 30, 城市: '上海' }
]
}
}
}
</script>
使用第三方组件库(如 Element UI)
通过 Element UI 的 el-table 组件快速实现功能丰富的表格。
<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-column prop="city" label="城市"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 25, city: '北京' },
{ name: '李四', age: 30, city: '上海' }
]
}
}
}
</script>
动态绑定样式
通过 Vue 的 class 和 style 绑定实现表格行的条件样式。
<template>
<table>
<tr v-for="(item, index) in items" :key="index"
:class="{ 'highlight': item.highlight }">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</template>
<style>
.highlight {
background-color: yellow;
}
</style>
添加交互功能
结合 Vue 的事件处理实现表格行点击等交互。
<template>
<table>
<tr v-for="(item, index) in items" :key="index"
@click="handleClick(item)">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</template>
<script>
export default {
methods: {
handleClick(item) {
console.log('Clicked:', item);
}
}
}
</script>
分页功能实现
通过计算属性实现表格数据的分页显示。
<template>
<table>
<tr v-for="(item, index) in paginatedItems" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
<button @click="prevPage">上一页</button>
<button @click="nextPage">下一页</button>
</template>
<script>
export default {
data() {
return {
currentPage: 1,
pageSize: 5
}
},
computed: {
paginatedItems() {
const start = (this.currentPage - 1) * this.pageSize;
return this.items.slice(start, start + this.pageSize);
}
},
methods: {
prevPage() { if (this.currentPage > 1) this.currentPage--; },
nextPage() { this.currentPage++; }
}
}
</script>






