0%

Element-Plus表格自适应列

记录一下element-plus表格自适应列宽度。

声明变量

1
const btnColumn = ref()

关联组件

1
2
3
4
5
6
7
<el-table-column>
<el-button-group ref="btnColumn">
<el-button v-for="(item, index) in buttons" :key="index">
{{ item.title }}
</el-button>
</el-button-group>
</el-table-column>

自适应宽度

  • 先打印查看元素是否捕获到
1
2
3
4
// 数据异步渲染需要更新组件后获取
onUpdated(() => {
console.log((btnColumn.value.$el as HTMLDivElement).querySelectorAll('button'))
})
  • 获取按钮宽度
1
2
3
4
5
onUpdated(() => {
let w = [...btnColumn.value.$el.querySelectorAll('button')].reduce((w, el) => {
return w + parseInt(getComputedStyle(el).width)
}, 0)
})
  • 设置边距并设置给单元格
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<el-table-column align="center" :width="btnGroupWidth">
<el-button-group ref="btnColumn">
<el-button v-for="(item, index) in buttons" :key="index">
{{ item.title }}
</el-button>
</el-button-group>
</el-table-column>

<script lang="ts" setup>
const btnGroupWidth = ref(0)
onUpdated(() => {
let w = [...btnColumn.value.$el.querySelectorAll('button')].reduce((w, el) => {
return w + parseInt(getComputedStyle(el).width)
}, 0)
// 设置边距
btnGroupWidth.value = w + 30
})
</script>