Moment For Technology

Use canvas to measure the real width of text to set the column width of each column in el-Table

Posted on Jan. 31, 2023, 9 a.m. by 段雅芳
Category: The front end Tag: element
First, listen on the data bound to the table in watch:
data(valArr) { const _this = this this.formThead = (value) { const arr = = Value. Width = _this.getMaxLength(arr) + 20 // The maximum width of each column Return value})}Copy the code
Calculate the maximum width of each column:
getMaxLength(arr) { String.prototype.pxWidth = function (font) { var canvas = String.prototype.pxWidth.canvas || (String.prototype.pxWidth.canvas = document.createElement('canvas')), context = canvas.getContext('2d') font  (context.font = font) var metrics = context.measureText(this) return metrics.width } return arr.reduce((acc, Item) = {if (item) {const calcLen = (item + '').pxWidth('bold 12pt Arial ') If (acc  calcLen) {acc = calcLen}} return acc}, 0)}Copy the code
About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.