vue 实现table组件
Vue 实现 Table 组件
基础表格结构
使用 Vue 的模板语法构建表格的基本框架,通过 v-for 动态渲染数据。
<template>
<table>
<thead>
<tr>
<th v-for="column in columns" :key="column.key">{{ column.title }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in data" :key="index">
<td v-for="column in columns" :key="column.key">{{ row[column.key] }}</td>
</tr>
</tbody>
</table>
</template>
动态数据绑定
通过 props 接收外部传入的数据和列配置,确保组件的复用性。
<script>
export default {
props: {
data: {
type: Array,
default: () => []
},
columns: {
type: Array,
default: () => []
}
}
};
</script>
支持自定义列模板
使用插槽(slot)允许用户自定义单元格内容,增强灵活性。
<template>
<table>
<thead>...</thead>
<tbody>
<tr v-for="(row, index) in data" :key="index">
<td v-for="column in columns" :key="column.key">
<slot :name="`column-${column.key}`" :row="row">
{{ row[column.key] }}
</slot>
</td>
</tr>
</tbody>
</table>
</template>
添加排序功能
通过事件触发排序逻辑,更新数据顺序。
<script>
export default {
methods: {
handleSort(column) {
this.data.sort((a, b) => {
if (a[column.key] > b[column.key]) return 1;
if (a[column.key] < b[column.key]) return -1;
return 0;
});
}
}
};
</script>
样式与交互优化
添加悬停效果和斑马纹样式,提升用户体验。
<style scoped>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
border: 1px solid #ddd;
}
tr:hover {
background-color: #f5f5f5;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
</style>
完整组件示例
整合上述功能,提供一个可直接复用的 Table 组件。
<template>
<table>
<thead>
<tr>
<th
v-for="column in columns"
:key="column.key"
@click="handleSort(column)"
>
{{ column.title }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in data" :key="index">
<td v-for="column in columns" :key="column.key">
<slot :name="`column-${column.key}`" :row="row">
{{ row[column.key] }}
</slot>
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
props: {
data: Array,
columns: Array
},
methods: {
handleSort(column) {
this.$emit('sort', column);
}
}
};
</script>
<style scoped>
/* 添加样式 */
</style>






