编辑
减少逐列控件绑定代码可使用 列级编辑与控件;主表单一次提交全部明细、虚拟离屏校验与受控新增见 外部表单与明细。本页聚焦 useTableEdit 的行草稿、校验与保存协议。
useTableEdit 按稳定行键管理行草稿、校验和异步保存。它不生成字段控件;页面可通过 bodyCell 接入现有 UI 控件。
本页包含行编辑示例和 useTableEdit 完整 API。
编辑状态与校验协议
useTableEdit 对齐 EditableProTable 的编辑协议:editableKeys 表示当前编辑行,保存完成后退出编辑,校验或保存失败保留草稿;onCancel 完成后丢弃草稿。add() 对应缓存新增行,取消后该行消失。新增按钮和操作列由业务组合。
本例使用 useTableEdit 的公开方法连接输入和操作按钮。edit.isEditing(key) 接收稳定行键,判断该行是否仍有编辑草稿;保存或取消等待期间,以及校验、保存或取消失败后保留草稿时,仍返回 true。
const edit = useTableEdit<Member>({
rowKey: 'key',
mode: 'multiple',
validate: (draft) => (draft.name.trim() ? undefined : { fields: { name: '请输入姓名' } }),
onSave: async (draft, { key, original, isNew, signal }) => {
const saved = await api.saveMember(draft, { signal })
// 使用 key 定位已有记录,isNew 时插入;original 是进入编辑时的快照。
updateDataSource(saved, { key, isNew, original })
return saved // 也可返回 true / void 接受草稿,返回 false 保持编辑。
},
})validate / toValue / onSave / onCancel 的 context 包含 key / original / isNew / signal;toDraft 不含 signal。cache 新增的 isNew 为 true、original 为 undefined,可在保存结果中使用服务端新 key;source 新增立即写入源数据,按已有行编辑,不能改 key。
输入期间只调用 setDraft(),不要直接改写源数据或 getDraft() 的返回值。保存期间相同行的重复调用复用同一 Promise,不会重复调用 onSave。取消或更新草稿会中止旧任务,过期的成功或失败不能关闭新草稿;组件作用域销毁会清理全部任务。异步业务回调仍须传递并检查 signal,防止已经取消的请求写回业务数据。
编辑状态位于组合式函数中,虚拟行离屏卸载不会丢失草稿。分页、刷新、数据替换也不会自动取消草稿;业务需要在离开页面、切换数据集或删除记录时明确调用 cancel / cancelAll。
手写控件的布局
直接使用 useTableEdit 并在 bodyCell 里手写控件时,把控件放进 VTableEditShell,进入编辑就不会改变列宽和行高,行为与列级编辑的布局稳定一致。
<VTable :columns="columns" :data-source="edit.records.value" row-key="id">
<template #bodyCell="cell">
<VTableEditShell
v-if="edit.isEditing(cell.record.id) && cell.column.dataIndex === 'name'"
:cell="cell"
:original="edit.getOriginal(cell.record.id)"
:error="edit.errors.value.get(cell.record.id)?.fields?.name"
error-placement="tooltip"
>
<Input
:value="edit.getDraft(cell.record.id)?.name"
@update:value="(name) => edit.setDraft(cell.record.id, { name })"
/>
</VTableEditShell>
</template>
</VTable>控件是多行文本框时,给 VTableEditShell 加上 fill,文本框会撑满单元格的高度,适合文本换行显示的列。
- 默认插槽放控件。控件会被拉伸到列宽,不需要自己设置宽度。
- 占位内容默认按列的展示规则渲染(
valueType、valueEnum、columnEmptyText等)。展示态由customRender或其他自定义内容渲染时,通过display插槽提供同样的内容,插槽参数是编辑前的单元格上下文。 - 表格的
dataSource是edit.records这类包含草稿的数据时,传入original,占位内容才不会随输入变化。 error由业务传入,errorPlacement的含义与useTableEditable相同。
能力边界
useTableEdit 已提供行级状态、校验和保存协议,以下能力仍由业务组合:
- 自动查询或编辑表单生成、字段间依赖联动。
- 整表事务提交、撤销历史或具体 HTTP 服务。
- Excel 式方向键、Tab 连续编辑和单元格选区。
需要字段联动时可组合项目现有的表单方案;需要完整电子表格式编辑引擎时,可考虑 vxe-table。
虚拟滚动
虚拟行离屏时编辑器会卸载,但 useTableEdit 的草稿仍按稳定行键保留;行重新挂载后可继续编辑。切换数据集或删除记录时,业务需调用 cancel / cancelAll。
API
以下汇总 useTableEdit<TRecord> 的全部配置、状态和方法。TRecord 是业务行类型;受控明细与一次提交的完整使用场景见明细表单。
useTableEdit 选项
行草稿与保存
异步校验、保存与取消使用的 context 为 { key, original, isNew, signal };toDraft 使用不含 signal 的 TableEditDraftContext<TRecord>。
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
rowKey | keyof TRecord | ((record: TRecord) => Key) | 必填 | 稳定的行键,字段名或返回 string / number 的函数;不使用行索引。 |
mode | 'single' | 'multiple' | 'single' | 单行模式已有草稿时,start 和 add 返回 false。 |
clone | (record: TRecord) => TRecord | 内置复制 | 完整记录的复制函数。默认复制普通对象、数组和 Date,记录含可变类实例时自行提供。 |
toDraft | (record: TRecord, context: TableEditDraftContext<TRecord>) => TRecord | - | 开始编辑时把源记录转换为草稿。每次 validateAll() 校验没有草稿的行时,也会调用它创建临时草稿。 |
toValue | (draft: TRecord, context: TableEditContext<TRecord>) => TRecord | - | 保存或读取提交值时把草稿转换回记录。 |
validate | (draft: TRecord, context: TableEditContext<TRecord>) => TableEditValidationErrors | void | Promise<TableEditValidationErrors | void> | - | (draft, context) 同步或异步返回 { message?, fields? };返回 void 或空对象继续保存。 |
onSave | (draft: TRecord, context: TableEditContext<TRecord>) => TRecord | void | boolean | Promise<TRecord | void | boolean> | - | 校验和转换后调用;返回记录或 true / void 接受,返回 false 保留编辑。配置 dataSource 与 onChange 时自动回写,否则由业务更新数据。 |
onCancel | (draft: TRecord, context: TableEditContext<TRecord>) => void | boolean | Promise<void | boolean> | - | (draft, context) 同步或异步的取消处理。返回 false 保留草稿,拒绝时记录 'cancel' 错误。 |
onError | (error: TableEditError, key: Key) => void | - | 校验、保存或取消失败时调用;错误同时可从 errors 读取。 |
受控源与新增
dataSource 与 onChange 连接父级源记录,createRecord 与 maxRows 配置新增行为。
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
dataSource | MaybeRefOrGetter<readonly TRecord[]> | - | 可选的受控源;配合 onChange 发布保存结果。省略时 records 只含编辑会话和缓存新增。 |
onChange | (records: TRecord[]) => void | - | 与 dataSource 配对;保存成功或 source 新增时调用,输入时不调用。 |
createRecord | () => TRecord | - | 无参调用 add() 时生成一条记录。 |
maxRows | number | - | 客户端持有的记录数上限,包含缓存的新增行。 |
useTableEdit 返回值
行状态与操作
| 属性或方法 | 类型 | 说明 |
|---|---|---|
editableKeys | ComputedRef<readonly Key[]> | 编辑中的行键;通过 start、add、cancel、save 变更。 |
savingKeys | ComputedRef<ReadonlySet<Key>> | 保存(含校验)中的行键,可用于禁用编辑器或显示 loading。 |
cancellingKeys | ComputedRef<ReadonlySet<Key>> | 取消处理中的行键。 |
errors | ComputedRef<ReadonlyMap<Key, TableEditError>> | 行键到 { type, message, fields?, cause? } 的映射。 |
newRecords | ComputedRef<TRecord[]> | 只含未保存的 cache 新增;records 已包含它们。source 新增需配 dataSource 与 onChange,立即写入源,不在此返回。 |
isEditing | (key: Key) => boolean | 按稳定行键判断行编辑会话;保存或取消等待中、失败保留草稿时仍为 true。会话成功结束或 reset 后为 false。 |
getDraft | (key: Key) => TRecord | undefined | 读取隔离的草稿副本;修改通过 setDraft 应用。 |
start | (record: TRecord) => boolean | 为已有记录创建草稿;行键重复时返回 false。 |
add | (record?: TRecord, config?: TableEditAddConfig) => boolean | 默认在尾部缓存新增行。省略 record 时调用 createRecord()。两者都未提供记录、行键重复、达到 maxRows 或单行模式已有草稿时返回 false。source 模式要求配置 dataSource 和 onChange。配置见下方 TableEditAddConfig。 |
setDraft | (key: Key, patch: Partial<TRecord> | ((draft: TRecord) => TRecord)) => boolean | 合并部分字段,或通过函数更新嵌套字段;清除旧错误并中止该行旧任务。未编辑或已销毁返回 false,修改行键同步抛错。 |
save | (key: Key) => Promise<TRecord | undefined> | 校验并保存。成功返回记录并结束编辑,失败或已失效返回 undefined。 |
cancel | (key: Key) => Promise<boolean> | 取消该行;成功后清理草稿和错误。 |
cancelAll | () => Promise<boolean[]> | 取消全部编辑中的行。 |
明细快照与全量校验
配置 dataSource 后,records 包含源记录和编辑草稿,可绑定到表格;配合 onChange 可在保存后回写。未传 dataSource 时只包含编辑会话和缓存新增行。主表单提交使用 validateAll() 返回的快照。
| 属性或方法 | 类型 | 说明 |
|---|---|---|
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 | 中止进行中的操作并清除草稿和错误,保留外部源记录。 |
TableEditAddConfig
add(record, config) 的第二个参数控制新增位置与缓存策略;省略 record 时由 createRecord() 提供记录。
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
position | 'top' | 'bottom' | 'bottom' | 新增行在客户端记录中的位置。 |
mode | 'cache' | 'source' | 'cache' | cache 在保存前保留为新增草稿,取消后移除;source 立即通过 onChange 插入受控源,取消编辑保留源记录。 |
VTableEditShell Props
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
cell | TableBodyCellSlotProps<TRecord> | 必填 | VTable bodyCell 的完整插槽上下文。 |
original | TRecord | cell.record | 编辑前的记录,例如 edit.getOriginal(key)。占位层按它渲染,草稿变化不会改变单元格尺寸。 |
layout | 'stable' | 'flow' | 'stable' | 编辑单元格的布局方式,含义同 useTableEditable 的 layout。 |
fill | boolean | false | 让控件撑满单元格的高度,用于多行文本框这类多行控件。仅在 stable 布局下生效。 |
error | string | - | 当前字段的错误文案。 |
errorPlacement | 'inline' | 'tooltip' | 'inline' | 错误的展示位置,含义同 useTableEditable 的 errorPlacement。 |
ui | Partial<Record<TableEditCellUiSlots, string>> | - | 覆盖当前单元格的编辑 slot class。 |
VTable Props
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
rowKey | string | ((record: TRecord) => Key) | 'key' | 行唯一标识。选择状态按行 key 记录,必须稳定且唯一。 |
dataSource | TRecord[] | [] | 表格数据源。 |
Type Declarations
TRecord 表示业务行类型。完整声明见类型参考。
查看类型声明
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 type Key = string | number