computed: {
tableRange() {
const { tableHeaderData, tableDataList } = this
return {
tableHeaderData,
tableDataList
}
}
},
watch: {
tableRange(val) {
const _this = this
const tableDataList = val.tableDataList.slice(0, 10)
const tableHeaderData = val.tableHeaderData
if (tableDataList.length === 0) return
var header = []
tableHeaderData.forEach((item, index) => {
header.push({ indexKey: index + 1 })
})
var obj = {}
header.forEach(header => {
obj[header.indexKey] = []
})
// 数据为空时,只获取表头的宽度自适应 // 数据不为空,全部数据宽度自适应
tableHeaderData.forEach((head, headIndex) => {
obj[headIndex + 1].push(head.description)
})
if (tableDataList.length > 0) {
tableDataList.forEach((row, rowIndex) => {
row.forEach((col, colIndex) => {
for (var key in obj) {
if (colIndex === Number(key)) {
obj[key].push(col.text)
}
}
})
})
}
var totalWidth = 60
tableHeaderData.forEach((value, index) => {
const curWidth = _this.$getMaxLength(obj[index + 1])
if (curWidth < 40) {
value.width = 80
totalWidth += 80
} else if (curWidth >= 50 && curWidth < 80) {
value.width = 130
totalWidth += 130
} else if (curWidth >= 80 && curWidth <= 100) {
value.width = 150
totalWidth += 150
} else if (curWidth > 400) {
value.width = 400
totalWidth += 400
} else {
value.width = curWidth + 40
totalWidth += curWidth + 40
}
})
const TABLECONTENT = document.getElementById('TABLECONTENT')
if (TABLECONTENT) {
// 总宽度占不满整个table时,执行以下
if (totalWidth < TABLECONTENT.offsetWidth) {
_this.tableHeaderData.map(function(value) {
value.width = 'auto'
})
}
}
}
},
html
<el-table-column
v-for="(header,columnIndex) in tableHeaderData"
:key="columnIndex"
ref="sortColumn"
:render-header="$labelHead"
:prop="header[`orderByColumnName`]"
:label="header.description"
// 重点在这里
:width="header.width"
show-overflow-tooltip
align="left">
<template slot-scope="scope">
...
</template>
</el-table-column>
main.js // 自适应table宽度,获取width
$getMaxLength(arr) {
if (arr) {
return arr.reduce((acc, item) => {
if (item) {
const calcLen = this.$getTextWidth(item)
if (acc < calcLen) {
acc = calcLen
}
}
return acc
}, 0)
} else {
return 0
}
},
$getTextWidth(str) {
let width = 0
const html = document.createElement('span')
html.innerText = str
html.className = 'getTextWidth'
document.querySelector('body').appendChild(html)
width = document.querySelector('.getTextWidth').offsetWidth
document.querySelector('.getTextWidth').remove()
return width
},

本文介绍了如何在Vue项目中使用ElementUi的表格组件实现宽度自适应。通过在`main.js`中进行配置,动态计算并调整表格列的宽度,确保表格在不同屏幕尺寸下都能保持良好的显示效果。
2564

被折叠的 条评论
为什么被折叠?



