Column Width Estimation
autoColWidths() — estimates column widths from a data sample using the Canvas API measureText. Useful for setting initial ColumnDef.width values in VirtualTable based on actual content.
function autoColWidths<T>(
cols: { key: string; title: string }[],
rows: T[],
options?: AutoColWidthsOptions,
): Map<string, number>Parameters
cols
{ key: string; title: string }[]
Column definitions — key and header title.
rows
T[]
Data rows to measure.
options
AutoColWidthsOptions
Optional settings — see below.
Estimation Options
AutoColWidthsOptions
font
string · default: '12px sans-serif'
CSS font string — should match your cell font.
padding
number · default: 24
Extra px added to measured width (accounts for cell padding).
minWidth
number · default: 60
Minimum column width in px.
maxWidth
number · default: 320
Maximum column width in px.
Return value
Map<string, number> — maps each column key to a pixel width.
Example
import { autoColWidths } from 'vue-virtual-scroller-kit'
import type { ColumnDef } from 'vue-virtual-scroller-kit'
const rawCols = [
{ key: 'id', title: 'ID' },
{ key: 'name', title: 'Name' },
{ key: 'email', title: 'Email' },
]
const widths = autoColWidths(rawCols, rows, {
font: '12px Inter, sans-serif',
padding: 24,
maxWidth: 400,
})
const columns: ColumnDef[] = rawCols.map((c) => ({
key: c.key,
title: c.title,
width: widths.get(c.key) ?? 120,
minWidth: 60,
}))SSR note:
autoColWidthsusesdocument.createElement('canvas')internally. In SSR environments wheredocumentis unavailable it falls back to a uniform width of120px.