Appearance
CrudForm
表单组件,将 fields 渲染为 Naive UI 表单,支持 Modal / Drawer 两种显示模式。
Props
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
form | UseCrudFormReturn<Row> | — | 表单状态(必填) |
fields | CrudField<Row>[] | — | 字段定义(必填) |
displayMode | 'modal' | 'drawer' | 'modal' | 显示模式 |
v-model:visible | boolean | false | Modal/Drawer 的显示状态 |
title | string | ((mode: 'create' | 'edit') => string) | 自动生成 | 标题(函数可按模式返回不同标题) |
resetOnClose | boolean | true | 关闭后是否 reset form + restoreValidation |
formProps | FormProps | — | 透传到 NForm |
modalProps | ModalProps | — | 透传到 NModal |
drawerProps | DrawerProps | — | 透传到 NDrawer |
drawerContentProps | DrawerContentProps | — | 透传到 NDrawerContent |
title 默认值
| 模式 | 默认标题 |
|---|---|
create | '新增' |
edit | '编辑' |
Emits
| 事件 | 参数 | 说明 |
|---|---|---|
update:visible | boolean | visible 双向绑定 |
submit | Partial<Row> | 验证通过后触发,数据来自 form.getSubmitData() |
cancel | — | 取消/关闭触发 |
行为说明
字段渲染
只渲染 form.visibleFields(由 visibleIn.editForm 过滤)。
验证
required: true自动补一个"必填"规则(${label}不能为空)- 不会覆盖你在
field.ui.overrides.editForm.formItem.rule中定义的自定义规则 - 提交时先调用
NForm.validate(),通过后才 emitsubmit
提交数据
submit 事件的 data 来自 form.getSubmitData():
| 模式 | data 内容 |
|---|---|
create | 整个 model |
edit | 仅 changedData(变更字段) |
关闭行为
resetOnClose 为 true 时(默认),关闭 Modal/Drawer 后:
- 调用
form.reset()清空 model - 调用
NForm.restoreValidation()清除验证状态
Slots
| Slot | Props | 说明 |
|---|---|---|
field-${key} | { field, model, mode, value } | 自定义某个表单字段 |
footer | { mode, dirty } | 自定义底部按钮区(默认:取消 + 保存) |
footer slot 示例
vue
<CrudForm :form="form" :fields="fields" v-model:visible="visible" @submit="handleSubmit">
<template #footer="{ mode, dirty }">
<NSpace justify="end">
<NButton @click="visible = false">取消</NButton>
<NButton type="primary" :disabled="mode === 'edit' && !dirty" attr-type="submit">
{{ mode === 'create' ? '创建' : '更新' }}
</NButton>
</NSpace>
</template>
</CrudForm>示例
vue
<script setup lang="ts">
import { AutoCrud } from '@uozi/vito-naive-ui'
import { NAlert, NText } from 'naive-ui'
import { ref } from 'vue'
import { createBasicAdapter } from './basic-adapter'
import { demoColumns, demoFields } from './basic-schema'
const { adapter } = createBasicAdapter()
const crudRef = ref<InstanceType<typeof AutoCrud> | null>(null)
</script>
<template>
<div style="display: flex; flex-direction: column; gap: 12px">
<NAlert
:bordered="false"
type="info"
>
<div>
这是一个最小的 <NText code>
AutoCrud
</NText> 示例:搜索(query.search)、分页、排序、表单(Modal)、新增/编辑/删除。
</div>
</NAlert>
<AutoCrud
ref="crudRef"
:adapter="adapter"
:fields="demoFields"
:columns="demoColumns"
search-query-key="search"
form-mode="modal"
show-selection
:show-actions-column="true"
/>
</div>
</template>ts
import type { CrudAdapter, CrudSort, ListResult } from '@uozi/vito-core'
import type { DemoQuery, DemoRow } from './basic-types'
function compare(a: unknown, b: unknown): number {
if (a === b)
return 0
if (a === null || a === undefined)
return -1
if (b === null || b === undefined)
return 1
if (typeof a === 'number' && typeof b === 'number')
return a - b
return String(a).localeCompare(String(b))
}
function sortRows(rows: DemoRow[], sort?: CrudSort | null): DemoRow[] {
if (!sort)
return rows
const dir = sort.order === 'descend' ? -1 : 1
return rows.slice().sort((ra, rb) => dir * compare((ra as any)[sort.field], (rb as any)[sort.field]))
}
function filterRows(rows: DemoRow[], query: DemoQuery): DemoRow[] {
const s = query.search ?? {}
const name = s.name?.trim() ?? null
const status = s.status ?? null
return rows.filter((r) => {
if (name && !r.name.toLowerCase().includes(name.toLowerCase()))
return false
if (status && r.status !== status)
return false
return true
})
}
function createSeed(): DemoRow[] {
const now = Date.now()
return [
{ id: 1, name: '示例 1', status: 'enabled', amount: 12.3, createdAt: now - 3600_000 },
{ id: 2, name: '示例 2', status: 'draft', amount: 45.6, createdAt: now - 7200_000 },
{ id: 3, name: '示例 3', status: 'disabled', amount: 78.9, createdAt: now - 10800_000 },
]
}
export function createBasicAdapter(initial?: DemoRow[]): {
adapter: CrudAdapter<DemoRow, DemoQuery>
reset: (next?: DemoRow[]) => void
getAll: () => DemoRow[]
} {
let db = (initial ?? createSeed()).slice()
let idSeq = db.reduce((m, r) => Math.max(m, r.id), 0) + 1
function getAll() {
return db.slice()
}
function reset(next?: DemoRow[]) {
db = (next ?? createSeed()).slice()
idSeq = db.reduce((m, r) => Math.max(m, r.id), 0) + 1
}
const adapter: CrudAdapter<DemoRow, DemoQuery> = {
getId(row) {
return row.id
},
async list(params): Promise<ListResult<DemoRow>> {
const filtered = filterRows(db, params.query)
const sorted = sortRows(filtered, params.sort)
const page = Math.max(1, params.page)
const pageSize = Math.max(1, params.pageSize)
const start = (page - 1) * pageSize
return {
items: sorted.slice(start, start + pageSize),
total: sorted.length,
}
},
async create(data): Promise<DemoRow> {
const row: DemoRow = {
id: idSeq++,
name: String((data as any)?.name ?? ''),
status: ((data as any)?.status ?? 'draft') as DemoRow['status'],
amount: Number((data as any)?.amount ?? 0),
createdAt: Date.now(),
}
db = [row, ...db]
return row
},
async update(id, data): Promise<DemoRow> {
const idx = db.findIndex(r => r.id === id)
if (idx < 0)
throw new Error(`记录不存在:${id}`)
const next: DemoRow = { ...db[idx], ...(data as any), id: db[idx].id }
db = db.slice()
db[idx] = next
return next
},
async remove(id): Promise<void> {
db = db.filter(r => r.id !== id)
},
}
return { adapter, reset, getAll }
}ts
import type { SelectOption } from 'naive-ui'
import type { DemoRow } from './basic-types'
import { cellDateTime, cellEnumTag, cellMoney, defineColumns, defineFields } from '@uozi/vito-naive-ui'
const statusOptions: SelectOption[] = [
{ label: '草稿', value: 'draft' },
{ label: '启用', value: 'enabled' },
{ label: '禁用', value: 'disabled' },
]
export const demoFields = defineFields<DemoRow>([
{
key: 'name',
label: '名称',
type: 'text',
required: true,
visibleIn: { searchForm: true, table: true, editForm: true },
ui: {
formControl: { placeholder: '输入名称' },
overrides: {
editForm: { formControl: { clearable: true } },
searchForm: { formControl: { clearable: true } },
},
},
},
{
key: 'status',
label: '状态',
type: 'select',
required: true,
visibleIn: { searchForm: true, table: true, editForm: true },
ui: {
options: statusOptions,
formControl: { options: statusOptions, clearable: true },
},
},
{
key: 'amount',
label: '金额',
type: 'money',
required: true,
visibleIn: { searchForm: false, table: true, editForm: true },
ui: {
formControl: { min: 0, step: 1, placeholder: '输入金额' },
},
},
{
key: 'createdAt',
label: '创建时间',
type: 'datetime',
visibleIn: { searchForm: false, table: true, editForm: false },
},
])
export const demoColumns = defineColumns<DemoRow>([
{ key: 'name', label: '名称', sortable: true, width: 220 },
{
key: 'status',
label: '状态',
width: 120,
render: cellEnumTag({
options: statusOptions,
typeMap: { draft: 'warning', enabled: 'success', disabled: 'error' },
}),
},
{
key: 'amount',
label: '金额',
width: 140,
render: cellMoney({ currency: 'CNY' }),
},
{
key: 'createdAt',
label: '创建时间',
width: 200,
render: cellDateTime(),
},
])ts
export interface DemoRow {
id: number
name: string
status: 'draft' | 'enabled' | 'disabled'
amount: number
createdAt: number
}
export interface DemoQuery {
search?: {
name?: string | null
status?: DemoRow['status'] | null
}
}