外部表单与明细草稿
useTableEdit 与 useTableEditable 都可以连接受控明细数组。父表单保存已提交的源记录,行输入保留在表格草稿中;全量提交时可以收集尚未逐行保存的草稿,包含虚拟离屏行。
受控源与草稿
const details = ref<Row[]>(initialRows)
const edit = useTableEditable<Row>({
rowKey: 'id',
mode: 'multiple',
columns,
controls,
dataSource: details,
onChange: (value) => {
details.value = value
},
})
const { records, errors, validating } = editrecords 是源记录、行草稿和缓存新增行的组合快照,直接绑定到表格。onChange 只在成功逐行保存或 source 模式新增时通知一次;逐键输入不回写源数据。父表单回写或服务端刷新不会覆盖已打开的本地草稿。删除源记录时,未结束的草稿仍保留在 records 中,避免静默丢失输入;业务确认放弃后调用 cancel 或 reset。
配置受控适配时,onSave 返回服务端的标准记录,由 onChange 更新父源;避免在两个回调中重复回写同一份数据。未配置适配时仍沿用原先由业务更新 dataSource 的方式。
getDraft(key) / getDrafts() 读取隔离的编辑器值,getOriginal(key) 读取进入编辑时的源快照。getValues() 组合当前客户端持有的数据并转换草稿为提交值,不触发校验、保存或 onChange。请使用 validateAll() 的结果快照执行最终提交,避免校验后又读取一份变化的数据。
一次提交明细
async function submitMaster() {
await masterForm.value.validate()
const result = await edit.validateAll()
if (!result.valid) {
const key = result.errors.keys().next().value
if (key !== undefined) await table.value.scrollTo({ key })
return
}
await saveOrder({ ...masterValues, details: result.values })
details.value = result.values!
edit.reset()
}外部提交的互斥、主表单校验与网络错误提示由业务控制。validateAll() 不调用 onSave / onChange,也不会关闭编辑或改变源数组;对未编辑源记录先临时转换为编辑器值再校验,提交结果仍保留其源值。发生输入、源数据变化、重置、保存或卸载时,旧校验返回 { valid: false, obsolete: true },不会覆盖新错误;相同进行中的校验合并。
错误保存在 errors 的行键和字段路径下,即使对应虚拟行已卸载仍可定位。validating 表示全量校验;逐行 savingKeys 表示保存,不能用循环 save 代替纯校验。校验失败或接口提交失败时保留用户草稿。
reset() 中止操作并清除草稿和错误,保留当前外部源数组;重置主表单时先替换 details,再调用 reset。它不执行取消回调,也不发送保存请求。
新增策略
const edit = useTableEditable<Row>({
rowKey: 'id',
mode: 'multiple',
columns,
controls,
dataSource: details,
onChange: (value) => {
details.value = value
},
createRecord: () => ({ id: nextLocalId--, name: '', amount: 1 }),
maxRows: 20,
})
edit.add(undefined, { position: 'top' })
edit.add(undefined, { position: 'bottom', mode: 'source' })默认 position: 'bottom' / mode: 'cache'。cache 新增在保存前只存在于草稿,取消即移除;source 模式立即通过 onChange 插入源数组,之后作为已有源行编辑,取消只丢弃编辑内容并保留这条源记录。source 需要 dataSource 和 onChange 配对配置。
createRecord 工厂每次尝试创建一个稳定且不重复的键;maxRows 统计当前客户端源与缓存新增行。达到上限、重复键或 single 模式已有编辑行时返回 false。已有行保存不能改键;缓存新行可由服务端分配最终键,但不能与现有源冲突。
这些能力仅覆盖客户端持有的记录:远程分页未加载的行无法校验;嵌套树节点插入由业务处理;服务端批量原子性、撤销历史和电子表格导航不包含在此协议中。
双预设完整演示位于 playground 的 /#/pro-schema,包含主表单、校验错误定位、保存失败保留、首尾新增和虚拟表体。
API
以下列出本页明细场景使用的选项和返回值。全部行编辑 API 集中在 useTableEdit 完整 API;列控件配置和接入见 useTableEditable API。
选项
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
dataSource | MaybeRefOrGetter<readonly TRecord[]> | - | 可选的受控源;配合 onChange 发布保存结果。省略时 records 只含编辑会话和缓存新增。 |
onChange | (records: TRecord[]) => void | - | 与 dataSource 配对;保存成功或 source 新增时调用,输入时不调用。 |
createRecord | () => TRecord | - | 无参调用 add() 时生成一条记录。 |
maxRows | number | - | 客户端持有的记录数上限,包含缓存的新增行。 |
返回值
| 属性或方法 | 类型 | 说明 |
|---|---|---|
records | ComputedRef<TRecord[]> | 有 dataSource 时包含源记录、草稿和缓存新增;无源时只含编辑会话和缓存新增。 |
validating | ComputedRef<boolean> | 是否正在执行全量校验。 |
getOriginal | (key: Key) => TRecord | undefined | 读取进入编辑时的源记录快照;缓存新增行返回 undefined。 |
getDrafts | () => ReadonlyMap<Key, TRecord> | 按行键读取隔离的草稿快照。 |
getValues | () => TRecord[] | 源记录加转换后的草稿,保留编辑状态,不调用保存。 |
validateAll | () => Promise<TableEditValidationResult<TRecord>> | 校验客户端持有的全部记录,返回同一次校验的提交快照,不保存。 |
reset | () => void | 中止进行中的操作并清除草稿和错误,保留外部源记录。 |
Type Declarations
查看类型声明
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>>
}