vue实现表格内容
Vue实现表格内容的方法
使用原生HTML表格
在Vue模板中直接使用HTML的<table>标签构建表格结构,通过v-for指令动态渲染数据。
<template>
<table>
<thead>
<tr>
<th v-for="(header, index) in headers" :key="index">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in rows" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职业'],
rows: [
['张三', 25, '工程师'],
['李四', 30, '设计师']
]
}
}
}
</script>
使用第三方组件库
通过集成Element UI或Ant Design Vue等UI库快速实现功能丰富的表格。
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-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>
<tr v-for="(item, index) in processedData" :key="index">
<td>{{ item.name }}</td>
<td :class="{ 'highlight': item.age > 28 }">{{ item.age }}</td>
</tr>
</table>
</template>
<script>
export default {
computed: {
processedData() {
return this.rawData.map(item => ({
...item,
status: item.age > 30 ? '资深' : '普通'
}))
}
},
data() {
return {
rawData: [
{ name: '王五', age: 35 },
{ name: '赵六', age: 27 }
]
}
}
}
</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 {
sortKey: '',
sortOrder: 1,
items: [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 }
]
}
},
computed: {
sortedData() {
return [...this.items].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>
虚拟滚动优化
对于大数据量表格,使用vue-virtual-scroller等插件优化性能。
<template>
<RecycleScroller
class="scroller"
:items="bigData"
:item-size="50"
key-field="id"
v-slot="{ item }"
>
<div class="row">
<span>{{ item.id }}</span>
<span>{{ item.name }}</span>
</div>
</RecycleScroller>
</template>
<script>
import { RecycleScroller } from 'vue-virtual-scroller'
export default {
components: { RecycleScroller },
data() {
return {
bigData: Array.from({ length: 1000 }, (_, i) => ({
id: i,
name: `项目 ${i}`
}))
}
}
}
</script>






