兩種方法:
方法一、計(jì)算文本內(nèi)容寬度,遍歷第一行數(shù)據(jù),取最寬的值,設(shè)置width屬性
計(jì)算文本有兩種方法
計(jì)算方法1,使用canvas計(jì)算,在有的瀏覽器可能不太準(zhǔn)確:
export function getTextWidth(text, font = 'normal 14px sans-serif') {
if (!text) {
return 0
}
// re-use canvas object for better performance
const canvas = getTextWidth.tCanvas || (getTextWidth.tCanvas = document.createElement('canvas'))
const context = canvas.getContext('2d')
context.font = font
return context.measureText(text).width + 2
}
計(jì)算方法2,把文本放入el-table表格取元素寬度,這個比第一個用canvas的方法更準(zhǔn)確,但要慢一些,因此用了緩存寬度加快速度:
<!--隱藏計(jì)算寬度組件-->
<el-table
ref="fit-table"
:row-height="40"
class="border fit-table"
:data="[{text:''}]"
:fit="false"
:show-header="false">
<el-table-column prop="text" width="1" />
</el-table>
/*計(jì)算寬度表格樣式*/
::v-deep .el-table.fit-table table.el-table__body {
font-family: "PingFang SC", "微軟雅黑", "Microsoft YaHei", "Helvetica Neue", Helvetica, "Hiragino Sans GB", Arial, sans-serif;
font-size: 14px;
table-layout: auto;
position: absolute;
top: -1000px;
visibility: hidden;
.cell {
white-space: nowrap;
}
}
//計(jì)算方法
const cachedCellWidth = {}
getCellWidth(text) {
if (!text) {
return 0
}
if (cachedCellWidth[text]) {
return cachedCellWidth[text]
}
if (this.$el) {
const fitCell = this.$el.querySelector('.fit-table .cell')
if (fitCell != null) {
fitCell.innerHTML = text
const width = fitCell.clientWidth + 2
cachedCellWidth[text] = width
return width
}
}
}
表格演示代碼,多行數(shù)據(jù)需遍歷計(jì)算最長的寬度,省略了自己寫一下吧
<template slot-scope="scope">
<el-table-column
:width="getTextWidth(scope.row.name) + 'px'"
:label="姓名"
:prop="name"
/>
</template>
方法二、設(shè)置表格樣式table-layout: 'auto',讓表格自適應(yīng)文本內(nèi)容,但需要根據(jù)單元格的寬度調(diào)整表頭的寬度。這個方法的幾個問題待優(yōu)化:
1、表格加載數(shù)據(jù)時,表頭寬度變化會閃爍一下
2、而且對于fixed屬性的單元格寬度計(jì)算有點(diǎn)問題
css樣式
table.el-table__body {
table-layout: auto;
}
.cell {
white-space: nowrap;
}
.el-table__fixed-body-wrapper table.el-table__body {
table-layout: fixed;
}
根據(jù)內(nèi)容調(diào)整表頭代碼
updated() {
setTimeout(() => {
const table = this.$refs['base-table'].$el
const colgroup = table.querySelector('.el-table__header colgroup')
const colDefs = colgroup.querySelectorAll('col')
colDefs.forEach(col => {
const clsName = col.getAttribute('name')
//獲取第一行單元格的寬度
const cell = table.querySelector(`.el-table__body td.${clsName}`)
if (cell) {
//設(shè)置表頭的寬度和單元格寬度一樣
const width = cell.clientWidth
col.setAttribute('width',width)
}
}, 300)
},