vue表格实现横向拉伸
实现横向拉伸的表格
在Vue中实现表格横向拉伸可以通过CSS和JavaScript结合实现,以下是几种常见方法:
使用CSS flex布局
通过设置flex-grow属性让表格列自动填充剩余空间:
<template>
<div class="table-container">
<table>
<tr>
<th v-for="(header, index) in headers" :key="index" class="flex-cell">
{{ header }}
</th>
</tr>
<tr v-for="(row, rowIndex) in rows" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex" class="flex-cell">
{{ cell }}
</td>
</tr>
</table>
</div>
</template>
<style>
.table-container {
width: 100%;
overflow-x: auto;
}
table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
}
.flex-cell {
flex: 1 1 0;
min-width: 100px;
}
</style>
使用百分比宽度
为每列设置百分比宽度实现均匀分布:
data() {
return {
headers: ['列1', '列2', '列3'],
columnWidths: ['33%', '33%', '33%']
}
}
<th v-for="(header, index) in headers" :key="index" :style="{ width: columnWidths[index] }">
可拖拽调整列宽
实现可交互的列宽调整功能:
<template>
<table>
<thead>
<tr>
<th v-for="(header, index) in headers" :key="index"
@mousedown="startResize(index, $event)">
{{ header }}
<div class="resizer" @mousedown.stop="startResize(index, $event)"></div>
</th>
</tr>
</thead>
<tbody>
<!-- 表格内容 -->
</tbody>
</table>
</template>
<script>
export default {
methods: {
startResize(index, e) {
document.addEventListener('mousemove', this.doResize)
document.addEventListener('mouseup', this.stopResize)
this.resizingIndex = index
this.startX = e.clientX
this.startWidth = this.$refs.headers[index].offsetWidth
},
doResize(e) {
const newWidth = this.startWidth + e.clientX - this.startX
this.columnWidths[this.resizingIndex] = `${newWidth}px`
},
stopResize() {
document.removeEventListener('mousemove', this.doResize)
document.removeEventListener('mouseup', this.stopResize)
}
}
}
</script>
<style>
.resizer {
width: 5px;
height: 100%;
background: #ddd;
cursor: col-resize;
position: absolute;
right: 0;
top: 0;
}
</style>
响应式表格
结合Vue的响应式特性和CSS实现自适应:
data() {
return {
tableWidth: '100%',
columns: [
{ width: 'auto', minWidth: '120px' },
{ width: '200px', minWidth: '150px' },
{ width: '300px', minWidth: '200px' }
]
}
}
<th v-for="(col, index) in columns" :key="index"
:style="{ width: col.width, minWidth: col.minWidth }">
以上方法可根据实际需求选择使用,CSS flex方案适合简单均匀分布,拖拽方案适合需要用户自定义的场景。







