Skip to content

列级编辑与宿主控件 ​

useTableEditable 在 useTableEdit 上增加列配置接线。它使用同一份草稿、错误和保存状态,通过 bodyCell 渲染注册的宿主控件,基础表格不自动进入编辑模式。

注册控件 ​

项目已经安装 Ant Design Vue 时,传入需要的组件:

ts
import { Input, Select, InputNumber, DatePicker, TimePicker } from 'ant-design-vue'
import { createAntdvTableControls } from '@vtable-guild/vtable-guild'

const controls = createAntdvTableControls({
  Input,
  Select,
  InputNumber,
  DatePicker,
  RangePicker: DatePicker.RangePicker,
  TimePicker,
})

Element Plus 使用相同的注册表协议:

ts
import {
  ElInput,
  ElSelect,
  ElOption,
  ElInputNumber,
  ElDatePicker,
  ElTimePicker,
} from 'element-plus'
import { createElementPlusTableControls } from '@vtable-guild/vtable-guild'

const controls = createElementPlusTableControls({
  Input: ElInput,
  Select: ElSelect,
  Option: ElOption,
  InputNumber: ElInputNumber,
  DatePicker: ElDatePicker,
  TimePicker: ElTimePicker,
})

这两个工厂只接收传入的组件,不导入 UI 库。由应用导入宿主组件样式。内置接线类型包括 text / textarea / select / enum / digit / money / date / dateRange / dateTime / dateTimeRange / time,查询和编辑可共享同一注册表。

editor.valueType 使用可扩展的 TableControlValueType。完整内置类型表、常用配置、自定义注册以及与展示类型的区别集中说明在 Schema 查询控件类型。

日期控件默认使用格式化字符串:date 为 YYYY-MM-DD,dateTime 为 YYYY-MM-DD HH:mm:ss,time 为 HH:mm:ss。范围类型返回两端数组。通过 fieldProps.valueFormat 覆盖;显式设为 undefined 可使用宿主原生日期对象。不同 UI 库的日期对象协议由应用转换。

Select 的控件值使用内部编码,更新时恢复字符串、数字和布尔值身份,false、'false'、1、'1' 不会混同。单选清除时,宿主返回的空值归一为 undefined;多选数组逐项还原,清空后的 [] 保留为空数组。宿主若返回非数组空值,则归一为 undefined。labelInValue 等其他值协议需要自定义 renderer。

配置与接入 ​

ts
import { ref } from 'vue'
import { useTableEditable, VTableEditCell, type TableColumnsType } from '@vtable-guild/vtable-guild'

interface Row {
  id: number
  name: string
  amount: number
  team: number
}
const rows = ref<Row[]>([{ id: 1, name: '明细 A', amount: 2, team: 1 }])
const columns: TableColumnsType<Row> = [
  {
    dataIndex: 'name',
    title: '名称',
    editor: {
      validate: (value) => (typeof value === 'string' && value.trim() ? undefined : '请输入名称'),
    },
  },
  {
    dataIndex: 'amount',
    title: '数量',
    valueType: 'digit',
    editor: {
      valueType: 'digit',
      fieldProps: { min: 1 },
      disabled: ({ draft }) => draft.team === 2,
    },
  },
  {
    dataIndex: 'team',
    title: '团队',
    valueEnum: { 1: '平台', 2: '交易' },
    editor: {
      valueType: 'select',
      options: [
        { value: 1, label: '平台' },
        { value: 2, label: '交易' },
      ],
    },
  },
]
const edit = useTableEditable({
  rowKey: 'id',
  mode: 'multiple',
  columns,
  controls,
  dataSource: rows,
  onChange: (value) => {
    rows.value = value
  },
  onSave: async (value) => value,
})
const { records } = edit
vue
<VTable :columns="columns" :data-source="records" row-key="id">
  <template #bodyCell="cell">
    <VTableEditCell v-if="edit.getCell(cell)" :edit="edit" :cell="cell" />
  </template>
</VTable>

模板中的 VTableEditCell 会补齐编辑器上下文,并在输入期间保持宿主控件的组件实例。TSX 的 bodyCell 插槽接收 text 和 index,调用 renderEditor 时须同时传入 value 和 renderIndex。沿用上面的 Row、columns、edit 和 records,可从组件的 setup 返回下面的 renderTable。

tsx
import { VTable, type TableBodyCellSlotProps } from '@vtable-guild/vtable-guild'

const bodyCell = (cell: TableBodyCellSlotProps<Row>) =>
  edit.renderEditor({ ...cell, value: cell.text, renderIndex: cell.index })

const renderTable = () => (
  <VTable<Row> rowKey="id" columns={columns} dataSource={records.value} v-slots={{ bodyCell }} />
)

当前单元格没有编辑器时,renderEditor 返回 undefined,表格继续使用原有的只读展示。模板中的 v-if="edit.getCell(cell)" 保留相同的回退行为。业务可在 bodyCell 中单独处理操作列,用宿主 UI 库的按钮和确认框调用 start(record)、save(key) 和 cancel(key)。列上配置的 customRender 优先于 bodyCell。

editor: false 或省略 editor 时,单元格保留只读展示。editor.editable / readonly / disabled 支持布尔值和按行上下文回调。在上述行编辑模式中,readonly 或 editable: false 使用只读展示,disabled 保留控件并禁止更新。转换与校验仍对所有配置了 editor 的字段执行。

点击单元格编辑 ​

沿用上例的 rows、columns 和 controls,将编辑初始化及模板改为下面的写法。

ts
const edit = useTableEditable<Row>({
  trigger: 'click',
  rowKey: 'id',
  columns,
  controls,
  dataSource: rows,
  onChange: (value) => {
    rows.value = value
  },
})
const { records } = edit
vue
<VTable :columns="columns" :data-source="records" row-key="id">
  <template #bodyCell="cell">
    <VTableEditCell v-if="edit.getCell(cell) || edit.canEditCell(cell)" :edit="edit" :cell="cell" />
  </template>
</VTable>

canEditCell(cell) 为允许编辑的单元格显示点击入口,getCell(cell) 让活动格继续显示控件和校验错误。编辑中若 editable 变为假,或 readonly / disabled 变为真,控件停止接受输入,并出现“取消编辑”按钮。条件恢复后可继续修正当前草稿。如果清空字段本身触发了限制,可以取消本次编辑,恢复原值后重新输入。

布局稳定 ​

进入编辑时,列宽和行高默认保持不变。编辑单元格里保留一份不可见的展示内容,由它决定单元格尺寸,控件叠在上面并撑满列宽。因此 table-layout: auto 的表格不会因为出现输入框而重新分配列宽,行也不会被控件撑高。

ts
const edit = useTableEditable<Row>({
  rowKey: 'id',
  columns,
  controls,
  layout: 'stable', // 默认值;'flow' 让控件按自身尺寸撑开单元格
  errorPlacement: 'tooltip', // 默认 'inline'
})
  • layout 和 errorPlacement 也可以作为 VTableEditCell 的属性传入,只作用于那一个单元格,优先级高于组合式函数的选项。
  • errorPlacement: 'inline' 时,错误在控件下方占一行,出错的行会变高,列宽不变。'tooltip' 时错误在悬停或聚焦单元格时以气泡提示,行高也不变;错误文本仍以 role="alert" 提供给读屏软件。
  • 不可见的那份内容按编辑前的记录渲染,输入过程中单元格尺寸不会跟着草稿变化。VTableEditCell 的默认插槽同时用于展示和占位,所以自定义展示内容(例如标签)应放进默认插槽,而不是写在 v-else 分支里:
vue
<VTableEditCell v-if="edit.getCell(cell)" :edit="edit" :cell="cell">
  <template #default="{ record }">
    <StatusTag :value="record.status" />
  </template>
</VTableEditCell>

使用前需要了解几点:

  • 展示内容会多渲染一份。它带有 aria-hidden,不可见也不可交互,但其中的组件会照常挂载;展示内容有副作用(请求、埋点)时,用 renderEditor 第三个参数的 sizer 或默认插槽换成纯展示的内容。
  • 控件宽度等于展示内容的宽度,也就是列宽减去单元格的左右内边距。这个宽度不足 --vtg-editor-min-inline-size(默认 64px)时,控件向左右内边距里外扩,最多扩到距单元格边缘 --vtg-editor-inset-inline(默认 2px)。列比控件自身的内边距和按钮还窄时,外扩之后内容仍然显示不全,需要给列设置 width / minWidth,或对这一格使用 layout="flow"。自动布局下只显示一两位数字的列最容易遇到;Element Plus 的数字输入框两侧的加减按钮固定占 84px,窄列里可以用 fieldProps: { controls: false } 关掉。
  • 控件高度不能超过行高减去上下各 --vtg-editor-inset-block(默认 2px)。两套预设的默认行高都能放下宿主的默认控件;Element Plus 的 size="small" 行高较小,需要同时使用小号控件(fieldProps: { size: 'small' })。需要多行输入时使用内置的 textarea,见多行文本;其他更高的控件请使用 layout="flow"。
  • 修改单元格的内边距时,同步覆盖 --vtg-table-cell-padding-block(上下)和 --vtg-table-cell-padding-inline(左右),控件才能正确地贴近单元格的边缘。
  • 依赖 CSS contain: inline-size,浏览器要求 Chrome / Edge 105、Safari 16、Firefox 121 及以上。

多行文本 ​

单元格里的文本换行显示时,把编辑器设为内置的 textarea。编辑框会撑满单元格:展示时有几行,编辑框就有几行高,文字在原来的位置按原来的宽度折行,列宽和行高都不变。

ts
const columns = [
  {
    dataIndex: 'remark',
    title: '备注',
    width: 240,
    editor: { valueType: 'textarea' },
    // 展示时保留文本里的换行
    customCell: () => ({ style: { whiteSpace: 'pre-line' } }),
  },
]
  • 回车换行,Ctrl + Enter(macOS 为 ⌘ + Enter)提交,Esc 取消。点击编辑时,失焦同样会提交。
  • 输入超出单元格的内容时,在编辑框内滚动;保存后行高按新内容重新计算。
  • 浏览器展示文本时默认把换行符折叠成空格。要让保存后的换行照原样显示,像上例那样用 customCell 给这一列设置 white-space: pre-line。
  • 编辑时文本框默认 rows: 1,空单元格里它和单行输入框一样高。用 fieldProps 设置更大的 rows 或 autoSize 后,文本框可能高于单元格,进入编辑时行高会随之变化。
  • Ant Design Vue 默认使用 Input.TextArea,Element Plus 使用 type="textarea" 的 ElInput。要换成别的组件,向控件工厂传 TextArea。

自己注册的多行控件加上 fill: true,也能撑满单元格:

ts
const controls = {
  ...createAntdvTableControls({ Input, Select, InputNumber, DatePicker }),
  markdown: Object.assign(
    (field: TableControlContext) => h(MarkdownInput, { ...field.fieldProps }),
    {
      fill: true,
    },
  ),
}

fill 把控件所在的层铺到整个单元格上,四边各留出编辑器的间隙,层内的直接子元素和 textarea 元素会随之填满。其他结构的控件需要自己设置 height: 100%。

转换、联动与校验 ​

convertValue(value, context) 在开始编辑时把源值转为控件值。点击编辑使用函数形式的 editable、readonly 或 disabled 时,入口判断也会读取转换后的字段和整行草稿。已有草稿会直接复用。每次执行 validateAll() 时,其余源行会调用 convertValue 生成用于校验的临时草稿。transform(value, context) 从草稿快照生成提交值,不改写用户正在输入的值。

dataIndex: ['profile', 'name'] 支持嵌套字段。字符串 dataIndex 按完整字段名读取,与只读表格一致。更新在隔离草稿上执行,禁止修改行键。包含可变类实例时,使用 clone(record) 定义快照行为。如果类用私有字段保存业务值,可以配置 isDraftEqual(draft, baseline),比较包括联动字段在内的整行数据。返回 true 表示已经改回打开时的状态,可以跳过保存。

onValueChange(value, context) 可以返回 Partial<Row> 联动其他字段,一次输入只更新一次草稿。上下文含 key / column / name / value / draft / original / isNew,其中 draft 和 original 是隔离副本。

保存先执行列 validate,字段规则通过后执行传入的行级 validate 一次,再进行提交转换与 onSave。字段校验返回字符串显示在控件下方;行级校验可返回 { message, fields },fields 使用点分字段路径。接宿主表单时,将表单 validate 放在行级 validate,避免在 onSave 再校验一次。失败保留草稿,savingKeys / cancellingKeys 禁用当前行的控件。

点击编辑时,commitCell(key) 校验当前列,save(key) 校验整行。如果失焦提交仍在校验,同行的 save(key) 会补验其余列,通过后才调用 onSave。如果单元格的 onSave 已经发出,组件会接收业务确认的记录和正式主键。补验失败时,行级调用返回 undefined,错误可从 errors 读取。

编辑期间替换响应式列配置时,commitCell(key) 按列键和字段路径查找最新的校验规则。如果已移除该列、撤销其 editor,或将该列改绑到另一个字段,提交会改为取消本次单元格编辑。原本就在编辑的行会恢复到进入该单元格时的草稿。

getCell(context) 返回完整控件上下文,支持自定义控件和插槽。注册业务类型只需返回 VNode:

ts
import { h } from 'vue'
import type { TableControls } from '@vtable-guild/vtable-guild'

const extendedControls: TableControls = {
  ...controls,
  project: (field) =>
    h(ProjectSelect, {
      modelValue: field.value,
      'onUpdate:modelValue': field.onChange,
      disabled: field.disabled,
    }),
}

editor.dictionary 可接 远程字典,自动提供 loading、选项与远程搜索,并保留已选标签。依赖参数在创建字典订阅时定义;清除或保留业务值由业务联动规则决定。显式 editor.options 优先于 dictionary 的候选项,包括空数组;未指定 options/dictionary 时,仅从同列 valueEnum 的字符串标签生成选项。数字、布尔文本和 VNode 标签需使用显式 options 或自定义控件。

控件、错误与间距通过 table 的 editCell / editControl / editError slots 及 --vtg-editor-* 变量配置,兼容两套预设。普通表格只增加列类型声明,不创建编辑器、表单或监听。

外部主表单一次提交、纯校验全部草稿、新增首尾与数量限制见 明细表单。

API ​

Column 字段 ​

字段类型默认值说明
valueTypestring-指定内置字段渲染类型或已注册的自定义类型。
fieldPropsTableFieldProps | ((context: CustomRenderContext<TRecord>) => TableFieldProps)-配置字段渲染器。支持对象和根据单元格上下文返回配置的函数。
editorfalse | TableColumnEditor<TRecord>-配置列编辑器。由 useTableEditable 读取,接入宿主控件和行草稿。

useTableEditable 配置 ​

useTableEditable<TRecord>(options) 继承 UseTableEditOptions<TRecord> 中除 toDraft / toValue 外的全部选项,包括 rowKey、mode、dataSource、onChange、校验及保存回调。完整行级选项见 useTableEdit API;值转换使用列的 editor.convertValue / transform。新增配置如下。

选项类型默认值说明
columnsMaybeRefOrGetter<ColumnsType<TRecord>>必填带 editor 配置的列。
controlsMaybeRefOrGetter<TableControls>必填宿主编辑控件映射。
trigger'manual' | 'click''manual'编辑触发模式;manual 为整行编辑,click 为悬停提示并点击单元格进入编辑。
showRowErrorbooleantrue单元格触发模式下,是否在活动单元格内回退显示行级保存/取消错误。
layout'stable' | 'flow''stable'编辑单元格的布局方式;stable 把控件叠在展示内容上,进入编辑时列宽和行高不变,flow 让控件按自身尺寸撑开单元格。
errorPlacement'inline' | 'tooltip''inline'字段错误的展示位置;inline 在控件下方占一行并撑高行,tooltip 在悬停或聚焦单元格时以气泡提示,行高不变。
isDraftEqual(draft: TRecord, baseline: TRecord) => boolean-比较当前整行草稿与打开单元格时的快照。返回 true 会跳过保存,可用于包含私有字段的业务类型。
uiPartial<Record<TableEditCellUiSlots, string>>-覆盖编辑单元格、控件容器、错误提示及点击触发器的 class。

useTableEditable 返回值 ​

返回值包含 useTableEdit 的全部状态和方法,例如 isEditing(key)、start(record)、save(key)、getValues() 和 validateAll(),以及以下单元格编辑 API。

方法类型说明
trigger'manual' | 'click'当前编辑触发模式。
layout'stable' | 'flow'解析后的编辑布局方式。
errorPlacement'inline' | 'tooltip'解析后的字段错误展示位置。
activeCellsComputedRef<ReadonlyMap<Key, TableEditableActiveCell>>单元格触发模式下各行当前激活的单元格映射。
canEditCell(context: Pick<CustomRenderContext<TRecord>, 'record' | 'column'>) => boolean判断单元格在未编辑态是否可点击进入编辑(检查 editor、editable、readonly 与 disabled)。
startCell(record: TRecord, column: ColumnType<TRecord>) => Promise<boolean>激活指定单元格编辑,先提交冲突的活动单元格。
commitCell(key: Key, column?: ColumnType<TRecord>) => Promise<boolean>提交活动单元格;整行草稿无变更时直接退出且不调用 onSave。
cancelCell(key: Key, column?: ColumnType<TRecord>) => Promise<boolean>取消活动单元格,保留借用草稿或缓存新增行。
uiPartial<Record<TableEditCellUiSlots, string>> | undefined透传给编辑单元格与触发器的 slot class 覆盖。
getCell(context: Pick<CustomRenderContext<TRecord>, 'record' | 'column'>) => TableEditableCellContext<TRecord> | undefined读取编辑控件上下文。没有草稿、没有 editor/dataIndex、editable=false 或 readonly=true 时返回 undefined,保留只读展示。
renderEditor(context: CustomRenderContext<TRecord>, ui?: Partial<Record<TableEditCellUiSlots, string>>, options?: TableEditRenderOptions<TRecord>) => VNodeChild渲染注册的宿主编辑器。第三个参数可按单元格覆盖 layout、errorPlacement,并用 sizer 自定义占位层内容。在 TSX 的 bodyCell 中传入 { ...cell, value: cell.text, renderIndex: cell.index }。没有编辑上下文时返回 undefined,表格继续使用只读展示。

TableEditableCellContext ​

getCell(context) 的返回上下文包含以下字段。渲染业务控件时读取 value / fieldProps / options,并使用 onChange 更新草稿。

字段类型说明
keyKey当前编辑行的稳定行键。
columnTableColumnType<TRecord>当前列定义。
draftTRecord隔离的行草稿副本;修改通过 onChange 或 setDraft 提交。
valueTypeTableControlValueType从列 editor、枚举或展示类型派生的控件键。
valueunknown当前字段的草稿值。
onChange(value: unknown) => void更新当前字段并执行 editor.onValueChange;禁用时忽略更新。
onSearch((keyword: string) => void) | undefined接入字典时用于远程搜索。
fieldPropsRecord<string, unknown>解析后的宿主控件属性。
optionsreadonly TableDictionaryOption[]显式选项、字典候选项或枚举派生选项,并补齐已知的已选标签。
disabledboolean列禁用条件或该行正在保存、取消时为 true。
readonlyboolean共享控件协议字段;getCell 返回的编辑上下文为 false,只读字段使用展示回退。
loadingboolean字典加载状态;未接字典时为 false。
errorstring | undefined当前字段的校验错误,或在单元格模式下回退显示行级错误。
idstring | undefined共享控件协议的可选 ID;当前列编辑接线不填充。
namestring | undefined字段路径;数组 dataIndex 转为点分路径。
mode'query' | 'edit'共享控件协议字段;列编辑为 edit。
lightFilter{ grouped: boolean; getPopupContainer: () => HTMLElement } | undefined共享控件协议的筛选弹层上下文;当前列编辑接线不填充。
cellEditTableControlCellEditBridge | undefined单元格触发编辑模式下的提交、取消与弹层状态桥接。
autoFocusTokennumber | undefined本次点击激活的一次性聚焦令牌,避免虚拟滚动或整行编辑抢焦点。
consumeAutoFocus((token: number) => boolean) | undefined消费一次性聚焦令牌,仅首次调用返回 true。

VTableEditCell Props ​

模板中传入 bodyCell 的完整上下文。行编辑模式使用 v-if="edit.getCell(cell)"。点击模式使用 v-if="edit.getCell(cell) || edit.canEditCell(cell)" 同时挂载编辑器和点击入口。

Prop类型默认值说明
editPick<UseTableEditableReturn<TRecord>, 'renderEditor'> & Partial<Pick<UseTableEditableReturn<TRecord>, 'trigger' | 'layout' | 'errorPlacement' | 'getCell' | 'canEditCell' | 'startCell' | 'ui'>>必填传入 useTableEditable 返回值,或提供同一 renderEditor 协议的对象。
cellTableBodyCellSlotProps<TRecord>必填VTable bodyCell 的完整插槽上下文。组件将 text/index 转为编辑渲染器的 value/renderIndex。
emptyTextstring-单元格点击编辑只读触发态为空时的兜底文案。
editIconbooleantrue是否在悬停或聚焦触发器时显示编辑图标。
layout'stable' | 'flow'-覆盖 useTableEditable 的 layout,只作用于当前单元格。
errorPlacement'inline' | 'tooltip'-覆盖 useTableEditable 的 errorPlacement,只作用于当前单元格。
uiPartial<Record<TableEditCellUiSlots, string>>-覆盖当前单元格的编辑或触发器 slot class。

TableColumnEditor ​

字段类型默认值说明
valueTypeTableControlValueType按列推断选择注册的编辑控件。未设置时,列有 valueEnum 则为 'select',否则取列的 valueType,都没有时为 'text'。
editableboolean | ((context: TableEditableFieldContext<TRecord>) => boolean)true返回 false 时沿用只读单元格。
readonlyboolean | ((context: TableEditableFieldContext<TRecord>) => boolean)false为 true 时沿用只读单元格。
disabledboolean | ((context: TableEditableFieldContext<TRecord>) => boolean)false保留编辑控件并禁止更新。
fieldPropsTableColumnEditor<TRecord>['fieldProps']{}传给宿主控件的属性或根据行上下文计算属性的函数。
optionsMaybeRefOrGetter<readonly TableDictionaryOption[]>字典或列枚举显式候选项。未设置时依次使用 dictionary 的候选项、列的 valueEnum。
dictionaryTableDictionaryBinding-提供字典候选项、加载状态和搜索。
convertValueTableColumnEditor<TRecord>['convertValue']-将源值转换为控件值。开始编辑、在无草稿的行上判断函数形式的编辑条件,以及用 validateAll() 校验该行时会执行转换。
transformTableColumnEditor<TRecord>['transform']-从草稿快照生成提交值,保留当前控件值。
validateTableColumnEditor<TRecord>['validate']-同步或异步校验字段。返回错误消息时保留草稿。
onValueChangeTableColumnEditor<TRecord>['onValueChange']-可返回其他字段的更新补丁。

主题 ​

使用实例 ui 或全局 theme.table.slots 调整编辑区域。宿主控件的外观沿用其 UI 库。

ui slots ​

Slot说明
editCell已进入编辑的单元格内容容器。
editSizer稳定布局下不可见的展示内容副本,决定编辑单元格的尺寸。
editControl宿主控件的宽度和错误轮廓。
editError按字段定位的校验错误。
editTrigger单元格点击编辑模式下的可点击触发按钮。
editTriggerValue单元格点击编辑触发器内的展示文本容器。
editTriggerIcon单元格悬停或聚焦时显示的编辑图标容器。

预设默认值 ​

ts
createVTableGuild({
  theme: {
    table: {
      slots: {
        editCell: 'min-w-0 data-[vtg-edit-layout=stable]:relative data-[vtg-edit-layout=stable]:flex data-[vtg-edit-layout=stable]:flex-1 data-[vtg-edit-layout=stable]:flex-wrap data-[vtg-edit-layout=stable]:items-center',
        editSizer: 'basis-full shrink-0 min-w-0 invisible pointer-events-none data-[vtg-edit-strut=true]:basis-0',
        editControl: 'min-w-0 [&>*]:w-full [&[data-vtg-edit-error=tooltip]>span>*]:w-full data-[vtg-edit-layout=stable]:basis-full data-[vtg-edit-layout=stable]:shrink-0 data-[vtg-edit-layout=stable]:[margin-inline-start:-100%] data-[vtg-edit-layout=stable]:[contain:inline-size] [&[data-vtg-edit-layout=stable]:not([data-vtg-edit-fill])]:[--vtg-edit-bleed-inline:clamp(0px,calc((var(--vtg-editor-min-inline-size)_-_100%)_/_2),max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline)))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])]:[--vtg-edit-bleed-inline:max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline))] [&[data-vtg-edit-layout=stable]>*]:mx-[calc(-1_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-layout=stable]>*]:w-[calc(100%_+_2_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])>*]:!mx-[calc(-1_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])>*]:!w-[calc(100%_+_2_*_var(--vtg-edit-bleed-inline,0px))] data-[vtg-edit-bleed=true]:my-[calc(var(--vtg-editor-inset-block)_-_var(--vtg-table-cell-padding-block))] data-[vtg-edit-fill=true]:self-stretch [&[data-vtg-edit-fill=true]_textarea]:!max-w-none [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:absolute [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:!m-0 [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:[inset-inline:calc(-1_*_max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline)))] [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:[inset-block:calc(var(--vtg-editor-inset-block)_-_var(--vtg-table-cell-padding-block))] [&[data-vtg-edit-fill=true]>*]:h-full [&[data-vtg-edit-fill=true][data-vtg-edit-error=tooltip]>span>*]:h-full [&[data-vtg-edit-fill=true]_textarea]:!h-full [&[data-vtg-edit-fill=true]_textarea]:!resize-none [&[data-vtg-edit-fill=true]_textarea]:![line-height:inherit] [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]_textarea]:!py-[calc(var(--vtg-table-cell-padding-block)_-_var(--vtg-editor-inset-block)_-_1px)] [&[data-vtg-edit-fill=true]_textarea]:!px-[calc(var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline)_-_1px)]',
        editError: 'block mt-[var(--vtg-editor-error-gap)] text-[length:var(--vtg-editor-error-font-size)] text-[color:var(--vtg-cell-error)] data-[vtg-edit-layout=stable]:basis-full data-[vtg-edit-layout=stable]:min-w-0 data-[vtg-edit-layout=stable]:whitespace-normal data-[vtg-edit-layout=stable]:[contain:inline-size] data-[vtg-edit-error=tooltip]:sr-only',
        editTrigger: 'group/edit-trigger flex w-full min-w-0 items-center gap-1.5 border-0 bg-transparent p-0 [text-align:inherit] [font:inherit] text-inherit cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[color:var(--color-primary)]',
        editTriggerValue: 'block min-w-0 flex-1',
        editTriggerIcon: 'shrink-0 text-[color:var(--color-primary)] opacity-0 transition-opacity group-hover/cell:opacity-100 group-hover/edit-trigger:opacity-100 group-focus-visible/edit-trigger:opacity-100',
      },
    },
  },
})
ts
createVTableGuild({
  themePreset: 'element-plus',
  theme: {
    table: {
      slots: {
        editCell: 'min-w-0 data-[vtg-edit-layout=stable]:relative data-[vtg-edit-layout=stable]:flex data-[vtg-edit-layout=stable]:flex-1 data-[vtg-edit-layout=stable]:flex-wrap data-[vtg-edit-layout=stable]:items-center',
        editSizer: 'basis-full shrink-0 min-w-0 invisible pointer-events-none data-[vtg-edit-strut=true]:basis-0',
        editControl: 'min-w-0 [&>*]:w-full [&[data-vtg-edit-error=tooltip]>span>*]:w-full [&[data-invalid=true]>*]:outline [&[data-invalid=true]>*]:outline-1 [&[data-invalid=true]>*]:outline-[color:var(--vtg-cell-error)] [&[data-invalid=true]>*]:rounded-[var(--vtg-editor-radius)] data-[vtg-edit-layout=stable]:basis-full data-[vtg-edit-layout=stable]:shrink-0 data-[vtg-edit-layout=stable]:[margin-inline-start:-100%] data-[vtg-edit-layout=stable]:[contain:inline-size] [&[data-vtg-edit-layout=stable]:not([data-vtg-edit-fill])]:[--vtg-edit-bleed-inline:clamp(0px,calc((var(--vtg-editor-min-inline-size)_-_100%)_/_2),max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline)))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])]:[--vtg-edit-bleed-inline:max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline))] [&[data-vtg-edit-layout=stable]>*]:mx-[calc(-1_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-layout=stable]>*]:w-[calc(100%_+_2_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])>*]:!mx-[calc(-1_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])>*]:!w-[calc(100%_+_2_*_var(--vtg-edit-bleed-inline,0px))] data-[vtg-edit-bleed=true]:my-[calc(var(--vtg-editor-inset-block)_-_var(--vtg-table-cell-padding-block))] data-[vtg-edit-fill=true]:self-stretch [&[data-vtg-edit-fill=true]_textarea]:!max-w-none [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:absolute [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:!m-0 [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:[inset-inline:calc(-1_*_max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline)))] [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:[inset-block:calc(var(--vtg-editor-inset-block)_-_var(--vtg-table-cell-padding-block))] [&[data-vtg-edit-fill=true]>*]:h-full [&[data-vtg-edit-fill=true][data-vtg-edit-error=tooltip]>span>*]:h-full [&[data-vtg-edit-fill=true]_textarea]:!h-full [&[data-vtg-edit-fill=true]_textarea]:!resize-none [&[data-vtg-edit-fill=true]_textarea]:![line-height:inherit] [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]_textarea]:!py-[calc(var(--vtg-table-cell-padding-block)_-_var(--vtg-editor-inset-block))] [&[data-vtg-edit-fill=true]_textarea]:!px-[calc(var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline))]',
        editError: 'block mt-[var(--vtg-editor-error-gap)] text-[length:var(--vtg-editor-error-font-size)] text-[color:var(--vtg-cell-error)] data-[vtg-edit-layout=stable]:basis-full data-[vtg-edit-layout=stable]:min-w-0 data-[vtg-edit-layout=stable]:whitespace-normal data-[vtg-edit-layout=stable]:[contain:inline-size] data-[vtg-edit-error=tooltip]:sr-only',
        editTrigger: 'group/edit-trigger flex w-full min-w-0 items-center gap-1.5 border-0 bg-transparent p-0 [text-align:inherit] [font:inherit] text-inherit cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[color:var(--color-primary)]',
        editTriggerValue: 'block min-w-0 flex-1',
        editTriggerIcon: 'shrink-0 text-[color:var(--color-primary)] opacity-0 transition-opacity group-hover/cell:opacity-100 group-hover/edit-trigger:opacity-100 group-focus-visible/edit-trigger:opacity-100',
      },
    },
  },
})

CSS 变量 ​

变量作用antdvelement-plus
--vtg-cell-error字段错误状态色,也用于查询和编辑校验文字#ff4d4f#f56c6c
--vtg-editor-inset-block稳定布局下控件与行上下边缘的最小间隙2px2px
--vtg-editor-inset-inline稳定布局下控件外扩时与单元格左右边缘的最小间隙2px2px
--vtg-editor-min-inline-size稳定布局下控件的期望最小宽度,不足时向单元格左右内边距外扩64px64px
--vtg-editor-error-gap控件与错误文字间距2px2px
--vtg-editor-error-font-size错误字号14px12px
--vtg-editor-radius编辑控件轮廓圆角不读取4px

Type Declarations ​

查看类型声明
ts
export {
  VTableEditCell,
  createAntdvTableControls,
  createElementPlusTableControls,
} from '@vtable-guild/vtable-guild'

export declare function useTableEdit<TRecord extends object>(
  options: UseTableEditOptions<TRecord>,
): UseTableEditReturn<TRecord>

export interface TableEditContext<TRecord extends object> {
  key: Key
  /** Snapshot from start(); undefined for a cached addition until it is saved. */
  original: TRecord | undefined
  isNew: boolean
  signal: AbortSignal
}

export type TableEditDraftContext<TRecord extends object> = Omit<
  TableEditContext<TRecord>,
  'signal'
>

export interface TableEditAddConfig {
  position?: 'top' | 'bottom'
  /** Cache until saved (default), or immediately insert into the controlled source. */
  mode?: 'cache' | 'source'
}

export interface TableEditValidationErrors {
  message?: string
  /** Field names or business-defined nested field paths. */
  fields?: Record<string, string>
}

export interface TableEditError extends TableEditValidationErrors {
  type: 'validation' | 'save' | 'cancel'
  message: string
  cause?: unknown
}

export interface TableEditValidationResult<TRecord extends object> {
  valid: boolean
  /** Submitted snapshots from this validation; absent for failures or obsolete work. */
  values?: TRecord[]
  errors: ReadonlyMap<Key, TableEditError>
  obsolete?: boolean
}

export interface UseTableEditOptions<TRecord extends object> {
  /** A stable key is required; row indexes are intentionally unsupported. */
  rowKey: keyof TRecord | ((record: TRecord) => Key)
  /** Defaults to single. Starting another row in single mode returns false. */
  mode?: 'single' | 'multiple'
  /** Override when records contain mutable class instances. */
  clone?: (record: TRecord) => TRecord
  /** Optional controlled source. Parent updates never replace an open local draft. */
  dataSource?: MaybeRefOrGetter<readonly TRecord[]>
  /** Commit notifications only; draft keystrokes never write back into the source. */
  onChange?: (records: TRecord[]) => void
  /** Convert a record when editing starts and when validateAll() validates a row without a draft. */
  toDraft?: (record: TRecord, context: TableEditDraftContext<TRecord>) => TRecord
  /** Convert an editor snapshot when saving or obtaining submitted values. */
  toValue?: (draft: TRecord, context: TableEditContext<TRecord>) => TRecord
  /** Used by add() when no explicit record is supplied. */
  createRecord?: () => TRecord
  /** Maximum client-held rows, including cached additions. Finite limits round down to an integer. */
  maxRows?: number
  /** Return errors to keep the draft open, or void to continue saving. */
  validate?: (
    draft: TRecord,
    context: TableEditContext<TRecord>,
  ) => TableEditValidationErrors | void | Promise<TableEditValidationErrors | void>
  /**
   * Return a canonical record, true/void to accept the submitted value, or false to keep editing.
   * With dataSource and onChange, return the saved record here and update the source in onChange.
   */
  onSave?: (
    draft: TRecord,
    context: TableEditContext<TRecord>,
  ) => TRecord | void | boolean | Promise<TRecord | void | boolean>
  /** Returning false or rejecting keeps the draft open. Cancellation aborts a pending save first. */
  onCancel?: (
    draft: TRecord,
    context: TableEditContext<TRecord>,
  ) => void | boolean | Promise<void | boolean>
  onError?: (error: TableEditError, key: Key) => void
}

export interface UseTableEditReturn<TRecord extends object> {
  /** Controlled source overlaid with local drafts and positioned cached additions. */
  records: ComputedRef<TRecord[]>
  validating: ComputedRef<boolean>
  editableKeys: ComputedRef<readonly Key[]>
  savingKeys: ComputedRef<ReadonlySet<Key>>
  cancellingKeys: ComputedRef<ReadonlySet<Key>>
  errors: ComputedRef<ReadonlyMap<Key, TableEditError>>
  /** Unsaved cache-mode additions. Source-mode additions are committed through onChange. */
  newRecords: ComputedRef<TRecord[]>
  isEditing: (key: Key) => boolean
  /** Returns an isolated copy. Use setDraft() to apply changes. */
  getDraft: (key: Key) => TRecord | undefined
  /** Source snapshot captured when editing began; undefined for cached additions or missing sessions. */
  getOriginal: (key: Key) => TRecord | undefined
  getDrafts: () => ReadonlyMap<Key, TRecord>
  /** Source records plus converted draft snapshots; never calls onSave or onChange. */
  getValues: () => TRecord[]
  /** Validate all client-held rows, including unmounted virtual rows, without saving. */
  validateAll: () => Promise<TableEditValidationResult<TRecord>>
  /** Abort operations and discard drafts/errors, retaining the current controlled source. */
  reset: () => void
  start: (record: TRecord) => boolean
  add: (record?: TRecord, config?: TableEditAddConfig) => boolean
  setDraft: (key: Key, patch: Partial<TRecord> | ((draft: TRecord) => TRecord)) => boolean
  /** Resolves undefined on validation/save failure, cancellation, or disposal. */
  save: (key: Key) => Promise<TRecord | undefined>
  cancel: (key: Key) => Promise<boolean>
  cancelAll: () => Promise<boolean[]>
}


export declare function useTableEditable<T extends object>(
  options: UseTableEditableOptions<T>,
): UseTableEditableReturn<T>

export interface TableEditableFieldContext<TRecord extends object> {
  key: Key
  name: string
  column: ColumnType<TRecord>
  draft: TRecord
  original?: TRecord
  value: unknown
  isNew: boolean
}
export interface TableColumnEditor<TRecord extends object> {
  /** Select a built-in or custom host control; omission uses the column's inferred control. */
  valueType?: TableControlValueType
  editable?: boolean | ((context: TableEditableFieldContext<TRecord>) => boolean)
  readonly?: boolean | ((context: TableEditableFieldContext<TRecord>) => boolean)
  disabled?: boolean | ((context: TableEditableFieldContext<TRecord>) => boolean)
  fieldProps?:
    | Record<string, unknown>
    | ((context: TableEditableFieldContext<TRecord>) => Record<string, unknown>)
  options?: MaybeRefOrGetter<readonly TableDictionaryOption[]>
  dictionary?: TableDictionaryBinding
  /** Convert source values for editing, dynamic entry conditions, and validation of undrafted rows. */
  convertValue?: (value: unknown, context: TableEditableFieldContext<TRecord>) => unknown
  /** Applied to a draft snapshot for saving/getValues, without rewriting the editor value. */
  transform?: (value: unknown, context: TableEditableFieldContext<TRecord>) => unknown
  validate?: (
    value: unknown,
    context: TableEditableFieldContext<TRecord> & { signal: AbortSignal },
  ) => string | void | Promise<string | void>
  /** A linked-field patch after the current field changes. */
  onValueChange?: (
    value: unknown,
    context: TableEditableFieldContext<TRecord>,
  ) => Partial<TRecord> | void
}
export type TableEditTrigger = 'manual' | 'click'

/**
 * - 'stable': the control is stacked over the display content, so entering edit mode
 *   changes neither the column width nor the row height.
 * - 'flow': the control takes part in layout with its own size.
 */
export type TableEditLayout = 'stable' | 'flow'

/**
 * - 'inline': the error takes a line below the control and makes the row taller.
 * - 'tooltip': the error is shown in a tooltip while the cell is hovered or focused.
 */
export type TableEditErrorPlacement = 'inline' | 'tooltip'

export interface TableEditRenderOptions<TRecord extends object> {
  /** Overrides the layout configured on useTableEditable for this cell. */
  layout?: TableEditLayout
  /** Overrides the error placement configured on useTableEditable for this cell. */
  errorPlacement?: TableEditErrorPlacement
  /**
   * Content of the hidden layer that keeps the cell at its display size in 'stable' layout.
   * Receives the cell as it was displayed before editing; defaults to the column's display rendering.
   */
  sizer?: (cell: TableBodyCellSlotProps<TRecord>) => VNodeChild
}

export interface TableEditableActiveCell {
  key: Key
  /** Stable column key (explicit column.key or normalized dataIndex key). */
  columnKey: Key
  /** Normalized field name matching TableEditableFieldContext.name and errors.fields keys. */
  name: string
}

export type TableEditCellUiSlots =
  | 'editCell'
  | 'editSizer'
  | 'editControl'
  | 'editError'
  | 'editTrigger'
  | 'editTriggerValue'
  | 'editTriggerIcon'

export interface TableEditableCellContext<TRecord extends object> extends TableControlContext {
  key: Key
  column: ColumnType<TRecord>
  draft: TRecord
  valueType: TableControlValueType
  /** Present for freshly activated cells so the editor focuses once without stealing focus on remounts. */
  autoFocusToken?: number
  consumeAutoFocus?: (token: number) => boolean
}
export interface UseTableEditableOptions<TRecord extends object> extends Omit<
  UseTableEditOptions<TRecord>,
  'toDraft' | 'toValue'
> {
  columns: MaybeRefOrGetter<ColumnsType<TRecord>>
  controls: MaybeRefOrGetter<TableControls>
  /**
   * Editing trigger mode:
   * - 'manual' (default): row-level editing via start() / save() / cancel().
   * - 'click': cell-level hover hint and click-to-edit managed through VTableEditCell.
   */
  trigger?: TableEditTrigger
  /** Show row-level save/cancel/validation message inside the active cell in cell-trigger mode. Defaults to true. */
  showRowError?: boolean
  /**
   * How an editing cell takes part in table layout:
   * - 'stable' (default): keeps the display size of the cell while editing.
   * - 'flow': sizes the cell by its control.
   */
  layout?: TableEditLayout
  /**
   * Where a field error is shown:
   * - 'inline' (default): below the control, which makes the row taller.
   * - 'tooltip': in a tooltip, leaving the row height unchanged.
   */
  errorPlacement?: TableEditErrorPlacement
  /** Compare the full edited row with its baseline, including domain-specific private state. */
  isDraftEqual?: (draft: TRecord, baseline: TRecord) => boolean
  ui?: Partial<Record<TableEditCellUiSlots, string>>
}
export interface UseTableEditableReturn<
  TRecord extends object,
> extends UseTableEditReturn<TRecord> {
  trigger: TableEditTrigger
  /** Resolved edit layout. */
  layout: TableEditLayout
  /** Resolved error placement. */
  errorPlacement: TableEditErrorPlacement
  /** Active cell sessions keyed by row key (empty in 'manual' mode). */
  activeCells: ComputedRef<ReadonlyMap<Key, TableEditableActiveCell>>
  /** Whether a cell can enter click-to-edit mode (checks editor, editable, readonly and disabled). */
  canEditCell: (context: Pick<CustomRenderContext<TRecord>, 'record' | 'column'>) => boolean
  /** Activate a specific cell for editing, committing any competing active cell first. */
  startCell: (record: TRecord, column: ColumnType<TRecord>) => Promise<boolean>
  /** Commit an active cell; unchanged drafts exit cleanly without calling onSave. */
  commitCell: (key: Key, column?: ColumnType<TRecord>) => Promise<boolean>
  /** Cancel an active cell, preserving borrowed drafts or cached additions. */
  cancelCell: (key: Key, column?: ColumnType<TRecord>) => Promise<boolean>
  /** Optional ui overrides configured on useTableEditable. */
  ui?: Partial<Record<TableEditCellUiSlots, string>>
  getCell: (
    context: Pick<CustomRenderContext<TRecord>, 'record' | 'column'>,
  ) => TableEditableCellContext<TRecord> | undefined
  /** Return from bodyCell; undefined retains VTable's normal readonly rendering. */
  renderEditor: (
    context: CustomRenderContext<TRecord>,
    ui?: Partial<Record<TableEditCellUiSlots, string>>,
    options?: TableEditRenderOptions<TRecord>,
  ) => VNodeChild
}

/** Documentation helper for VTableEditCell props; this interface is not a package export. */
export interface VTableEditCellProps<TRecord extends object = Record<string, unknown>> {
  edit: Pick<UseTableEditableReturn<TRecord>, 'renderEditor'> &
    Partial<
      Pick<
        UseTableEditableReturn<TRecord>,
        'trigger' | 'layout' | 'errorPlacement' | 'getCell' | 'canEditCell' | 'startCell' | 'ui'
      >
    >
  cell: TableBodyCellSlotProps<TRecord>
  emptyText?: string
  editIcon?: boolean
  /** Overrides the layout configured on useTableEditable for this cell. */
  layout?: TableEditLayout
  /** Overrides the error placement configured on useTableEditable for this cell. */
  errorPlacement?: TableEditErrorPlacement
  ui?: Partial<Record<TableEditCellUiSlots, string>>
}

/** Documentation helper for VTableEditShell props; this interface is not a package export. */
export interface VTableEditShellProps<TRecord extends object = Record<string, unknown>> {
  /** The bodyCell slot context of the cell being edited. */
  cell: TableBodyCellSlotProps<TRecord>
  /** The record as it was before editing, e.g. edit.getOriginal(key). Defaults to cell.record. */
  original?: TRecord
  layout?: TableEditLayout
  /** Stretch the control to the height of the cell; for a multi-line control such as a textarea. */
  fill?: boolean
  error?: string
  errorPlacement?: TableEditErrorPlacement
  ui?: Partial<Record<TableEditCellUiSlots, string>>
}