<el-table :key="key" :data="data" v-loading="loading" style="width: 100%;" >
<el-table-column v-for="item in formThead"
:key="item.prop"
:label="item.label"
:width="item.width" <!-- 设置宽度 -->
show-overflow-tooltip>
<template slot-scope="scope">
{{ scope.row[fruit.prop] }}
</template>
</el-table-column>
</el-table>
<script>
let colList = [
{ prop: "fy", label: "费用收取方式" },
{ prop: "product", label: "产品大类" },
{ prop: "tc", label: "投产策略" },
{ prop: "zkq", label: "子客群" },
{ prop: "custExistenceType", label: "首续贷" },
{ prop: "repayType", label: "还款方式" },
{ prop: "loanType", label: "抵押类型" },
{ prop: "irr", label: "IRR" },
{ prop: "beginTerm", label: "开始期次" },
{ prop: "endTerm", label: "结束期次" },
]
export default {
data() {
return {
colList: colList, // 默认表头 Default header
list: []
};
},
methods: {
* 遍历列的所有内容,获取最宽一列的宽度
getMaxLength (arr) {
return arr.reduce((acc, item) => {
if (item) {
let calcLen = this.getTextWidth(item)
if (acc < calcLen) {
acc = calcLen
}
}
return acc
}, 0)
},
* 使用span标签包裹内容,然后计算span的宽度 width: px
getTextWidth(str) {
let width = 0;
let 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;
}
},
watch: {
* 监控表格的数据data,自动设置表格宽度
data(valArr) {
const _this = this
this.formThead = colList.map(function (value) {
const arr = valArr.map(x => x[value.prop]) // 获取每一列的所有数据
arr.push(value.label) // 把每列的表头也加进去算
value.width = _this.getMaxLength(arr) + 20 // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
return value
})
}
}
}
</script>