vue实现table封装
Vue实现Table封装方法
封装一个可复用的Table组件是Vue项目中常见的需求,以下是一个基于Element UI或Ant Design Vue的封装方案:
基础Table封装
<template>
<el-table
:data="tableData"
:border="border"
:stripe="stripe"
@selection-change="handleSelectionChange"
>
<template v-for="(col, index) in columns">
<el-table-column
v-if="col.type"
:key="index"
:type="col.type"
:width="col.width"
/>
<el-table-column
v-else
:key="index"
:prop="col.prop"
:label="col.label"
:width="col.width"
>
<template #default="scope">
<slot :name="col.prop" :row="scope.row">
{{ scope.row[col.prop] }}
</slot>
</template>
</el-table-column>
</template>
</el-table>
</template>
<script>
export default {
props: {
tableData: {
type: Array,
default: () => []
},
columns: {
type: Array,
default: () => []
},
border: Boolean,
stripe: Boolean
},
methods: {
handleSelectionChange(val) {
this.$emit('selection-change', val)
}
}
}
</script>
使用示例
<template>
<CustomTable
:table-data="data"
:columns="columns"
border
stripe
@selection-change="handleSelect"
>
<template #status="{ row }">
<el-tag :type="row.status | statusType">
{{ row.status }}
</el-tag>
</template>
</CustomTable>
</template>
<script>
export default {
data() {
return {
data: [...],
columns: [
{ type: 'selection', width: 55 },
{ prop: 'name', label: '姓名' },
{ prop: 'age', label: '年龄' },
{ prop: 'status', label: '状态' }
]
}
}
}
</script>
高级功能扩展
分页处理
<template>
<div>
<el-table ... />
<el-pagination
:current-page="currentPage"
:page-size="pageSize"
:total="total"
@current-change="handlePageChange"
/>
</div>
</template>
动态列配置
props: {
showColumns: {
type: Array,
default: () => [],
validator: value => value.every(item => typeof item === 'string')
}
},
computed: {
filteredColumns() {
return this.columns.filter(col =>
this.showColumns.includes(col.prop) || col.type
)
}
}
排序和筛选
<el-table-column
:prop="col.prop"
:label="col.label"
sortable
:filters="col.filters"
:filter-method="col.filterMethod"
/>
性能优化技巧
使用v-if控制列的显示而非v-for的v-show,避免不必要的渲染
大数据量时考虑虚拟滚动方案,可使用vue-virtual-scroller等库
复杂单元格内容使用作用域插槽时,考虑提取为单独组件

对于固定列场景,合理设置fixed属性并注意浏览器兼容性






