vue实现表格拖动列宽
实现表格列宽拖动的核心思路
通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽逻辑。在表头列分隔线处添加可拖拽区域,拖动时动态修改列宽度。
HTML结构示例
<table>
<thead>
<tr>
<th v-for="(col, index) in columns" :key="index">
<div class="header-content">{{ col.title }}</div>
<div
class="resize-handle"
@mousedown="startResize(index, $event)"
></div>
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in data" :key="rowIndex">
<td v-for="(col, colIndex) in columns" :key="colIndex">
{{ row[col.key] }}
</td>
</tr>
</tbody>
</table>
CSS样式关键部分
th {
position: relative;
min-width: 80px;
}
.resize-handle {
position: absolute;
top: 0;
right: 0;
width: 5px;
height: 100%;
cursor: col-resize;
background-color: transparent;
z-index: 1;
}
.resize-handle:hover {
background-color: #ccc;
}
Vue组件实现逻辑
export default {
data() {
return {
columns: [
{ title: '姓名', key: 'name', width: 150 },
{ title: '年龄', key: 'age', width: 100 },
{ title: '地址', key: 'address', width: 300 }
],
data: [...],
isResizing: false,
currentColumn: null,
startX: 0,
startWidth: 0
}
},
methods: {
startResize(index, event) {
this.isResizing = true
this.currentColumn = index
this.startX = event.clientX
this.startWidth = this.columns[index].width
document.addEventListener('mousemove', this.handleResize)
document.addEventListener('mouseup', this.stopResize)
event.preventDefault()
},
handleResize(event) {
if (!this.isResizing) return
const dx = event.clientX - this.startX
this.columns[this.currentColumn].width = this.startWidth + dx
},
stopResize() {
this.isResizing = false
document.removeEventListener('mousemove', this.handleResize)
document.removeEventListener('mouseup', this.stopResize)
}
}
}
动态绑定列宽
修改HTML中的th和td元素,绑定动态宽度:
<th
v-for="(col, index) in columns"
:key="index"
:style="{ width: col.width + 'px' }"
>
...
</th>
<td
v-for="(col, colIndex) in columns"
:key="colIndex"
:style="{ width: columns[colIndex].width + 'px' }"
>
...
</td>
性能优化建议
使用CSS的user-select: none防止拖动时选中文本:
.resize-handle {
user-select: none;
}
对于大数据量表格,考虑使用虚拟滚动技术减少DOM节点数量。可以使用第三方库如vue-virtual-scroller实现。
第三方库方案
若不想手动实现,可使用现成组件库:

- Element UI的
el-table自带列宽拖动功能 - VxeTable提供完善的列宽调整API
- Handsontable等专业表格库
这些库通常提供更完善的边界处理、最小宽度限制、列宽记忆等功能。






