DynamicInput 动态录入
录入一组数量不定的数据:每行右侧有“+”“-”按钮,可以随时插入、删除,也可以上移、下移调整顺序。适合填多个网址、请求参数、联系人这类列表。
本页所有行删除(包括空行)均先确认;取消、关闭或按 Esc 不改数据。等待期间集合、行内容、只读状态变化或示例卸载,会作废旧确认。公开 remove 方法不自动调用 beforeRemove,用户按钮须先复用同一确认守卫。
引入
import { HuiDynamicInput } from '@nscode/handy-ui'
自持状态与受控回填
未传modelValue或仅监听更新时从空数组保存行;传入属性(含undefined)即受控,父拒绝时列表保持父值。新增、编辑、移动和删除保留稳定行key;同批请求合并,跨批读取实际状态。内部对象行支持插槽直接修改属性,切换受控模式会取消旧删除钩子等待。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiButton, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
const q1Redraw = ref(0)
const q1Last = ref('尚无请求')
const q1Model = ref<string[]>([])
const q1LocalRows = ref<string[]>([])
const q1ListenerRows = ref<string[]>([])
const recordListenerRows = (rows: string[]) => {
q1Last.value = JSON.stringify(rows)
q1ListenerRows.value = rows
}
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation<string>(
() => q1LocalRows.value,
() => false
)
const confirmRemove1 = createRemovalConfirmation<string>(
() => q1ListenerRows.value,
() => false
)
const confirmRemove2 = createRemovalConfirmation<string>(
() => [],
() => false
)
const confirmRemove3 = createRemovalConfirmation<string>(
() => ['甲'],
() => false
)
const confirmRemove4 = createRemovalConfirmation<string>(
() => q1Model.value,
() => false
)
</script>
<template>
<div class="dynamic-input-q1-demo">
<HuiButton class="q1-redraw" @click="q1Redraw++">父重绘 {{ q1Redraw }}</HuiButton
><HuiSpace direction="vertical" fill>
<div>
<p>未传属性,自行保存</p>
<div class="q1-local">
<HuiDynamicInput
:before-remove="confirmRemove0"
@update:model-value="q1LocalRows = $event"
:max="3"
show-sort-button
/>
</div>
</div>
<div>
<p>仅监听更新,仍自行保存</p>
<div class="q1-listener">
<HuiDynamicInput
:before-remove="confirmRemove1"
:max="3"
show-sort-button
@update:model-value="recordListenerRows"
/>
</div>
</div>
<div>
<p>显式undefined,父值优先</p>
<div class="q1-empty">
<HuiDynamicInput
:before-remove="confirmRemove2"
:max="3"
show-sort-button
:model-value="undefined"
/>
</div>
</div>
<div>
<p>固定受控,父拒绝更新</p>
<div class="q1-fixed">
<HuiDynamicInput
:before-remove="confirmRemove3"
:max="3"
show-sort-button
:model-value="['甲']"
@update:model-value="q1Last = JSON.stringify($event)"
/>
</div>
</div>
<div>
<p>双向绑定</p>
<div class="q1-bound">
<HuiDynamicInput
:before-remove="confirmRemove4"
:max="3"
show-sort-button
v-model="q1Model"
/>
</div>
</div>
<p class="q1-notification">绑定值:{{ q1Model }};最近请求:{{ q1Last }}</p></HuiSpace
>
</div>
</template>
基础用法
v-model 绑定一个数组,一项对应一行。默认的 preset="input" 每行一个文本框,值是字符串数组。点某一行的“+”在这一行下面插入一个空行,点“-”删除这一行。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
const cities = ref(['北京', '上海'])
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => cities.value,
() => false
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiDynamicInput :before-remove="confirmRemove0" v-model="cities" placeholder="请输入城市" />
<span>绑定值:{{ cities }}</span>
</HuiSpace>
</template>
键值对
preset="pair" 每行键、值两个文本框,值是 { key, value } 数组,常用来录入请求参数、请求头、环境变量。key-placeholder、value-placeholder 改两个文本框的占位文字。改键或值时只替换这两个属性,这一行上的其他属性(比如 id)会保留。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
import type { DynamicInputPair } from '@nscode/handy-ui'
const params = ref<DynamicInputPair[]>([
{ key: 'page', value: '1' },
{ key: 'size', value: '20' }
])
const headers = ref<DynamicInputPair[]>([{ key: 'Accept', value: 'application/json' }])
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => params.value,
() => false
)
const confirmRemove1 = createRemovalConfirmation(
() => headers.value,
() => false
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiDynamicInput :before-remove="confirmRemove0" v-model="params" preset="pair" />
<span>请求参数:{{ params }}</span>
<HuiDynamicInput
:before-remove="confirmRemove1"
v-model="headers"
preset="pair"
key-placeholder="请求头名称"
value-placeholder="请求头的值"
/>
<span>请求头:{{ headers }}</span>
</HuiSpace>
</template>
自定义行
两种预设不够用时,在默认插槽里写每一行的内容。插槽参数:
value:这一行的值;index:这一行的下标,从 0 开始。update(newValue):用新值替换这一行。remove():删除这一行(受min和禁用限制)。size、disabled:组件当前的尺寸和禁用状态,传给行里的控件,它们就能跟着组件一起变。
自定义行时要传 on-create,返回新增一行时的初始值,参数是新行的下标。每次都返回一个新对象,不要返回同一个对象,否则几行会共用它。
下面是联系人列表,每行是姓名、手机号和关系。行的值是对象,可以直接 v-model="value.name" 改它的属性。插槽内容在一行里横排,几个控件之间自动留出间距;文本框默认占满剩下的宽度,选择框用 style 给了固定宽度。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiInput, HuiSelect, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
import type { SelectOption } from '@nscode/handy-ui'
interface Contact {
name: string
phone: string
relation?: string
}
const relations: SelectOption[] = [
{ label: '父母', value: 'parent' },
{ label: '配偶', value: 'spouse' },
{ label: '子女', value: 'child' },
{ label: '朋友', value: 'friend' }
]
const contacts = ref<Contact[]>([{ name: '张三', phone: '13800000000', relation: 'friend' }])
const createContact = (): Contact => ({ name: '', phone: '', relation: undefined })
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => contacts.value,
() => false
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiDynamicInput :before-remove="confirmRemove0" v-model="contacts" :on-create="createContact">
<template #default="{ value, index }">
<HuiInput
v-model="value.name"
placeholder="姓名"
:aria-label="`第 ${index + 1} 位联系人的姓名`"
/>
<HuiInput
v-model="value.phone"
placeholder="手机号"
:aria-label="`第 ${index + 1} 位联系人的手机号`"
/>
<HuiSelect
v-model="value.relation"
:options="relations"
placeholder="关系"
:aria-label="`第 ${index + 1} 位联系人的关系`"
style="width: 120px; flex: none"
/>
</template>
</HuiDynamicInput>
<span>绑定值:{{ contacts }}</span>
</HuiSpace>
</template>
行的值是数字、字符串这类基本类型时不能直接改属性,要用 update 替换整行。下面每行是一个数字输入框:
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiInputNumber, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
const prices = ref<(number | undefined)[]>([99, 199])
const total = () => prices.value.reduce<number>((sum, price) => sum + (price ?? 0), 0)
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => prices.value,
() => false
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiDynamicInput :before-remove="confirmRemove0" v-model="prices" :on-create="() => undefined">
<template #default="{ value, index, update }">
<HuiInputNumber
:model-value="value"
:min="0"
:aria-label="`第 ${index + 1} 个价格`"
style="flex: 1"
@update:model-value="update"
/>
</template>
</HuiDynamicInput>
<span>绑定值:{{ prices }},合计 {{ total() }} 元</span>
</HuiSpace>
</template>
空状态和文字
一行都没有时显示一个虚线的“添加一项”按钮,add-text 改它的文字。placeholder 改 input 预设文本框的占位文字。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
const empty = ref<string[]>([])
const sites = ref<string[]>([])
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => empty.value,
() => false
)
const confirmRemove1 = createRemovalConfirmation(
() => sites.value,
() => false
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiDynamicInput :before-remove="confirmRemove0" v-model="empty" />
<HuiDynamicInput
:before-remove="confirmRemove1"
v-model="sites"
add-text="添加网址"
placeholder="https://"
/>
<span>网址:{{ sites }}</span>
</HuiSpace>
</template>
最少最多行数
min 是最少几行,行数等于它时“-”按钮禁用;max 是最多几行,行数等于它时所有“+”按钮禁用。min 默认 0,max 不传时不限制。组件不会自动补齐到 min 行,需要的话初始值就给够行数。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
const atLeastOne = ref(['只剩一行时不能删'])
const upToThree = ref(['第 1 个', '第 2 个'])
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => atLeastOne.value,
() => false
)
const confirmRemove1 = createRemovalConfirmation(
() => upToThree.value,
() => false
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<span>min = 1:</span>
<HuiDynamicInput :before-remove="confirmRemove0" v-model="atLeastOne" :min="1" />
<span>max = 3(已有 {{ upToThree.length }} 个):</span>
<HuiDynamicInput :before-remove="confirmRemove1" v-model="upToThree" :max="3" />
</HuiSpace>
</template>
删除前确认
beforeRemove 由业务决定是否允许删除。本例有内容和空行都先确认,只有返回 false、抛错或拒绝才拦截,undefined 放行。取消、关闭或按 Esc 返回 false。等待期间同一行不会重复打开确认;其他行仍可分别请求。确认保护同步观察列表及行内容,发生变化后旧结果不再放行。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiMessageBox } from '@nscode/handy-ui'
const values = ref(['已经填写的内容', ''])
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const beforeRemove = createRemovalConfirmation(
() => values.value,
() => false
)
</script>
<template>
<HuiDynamicInput :before-remove="beforeRemove" v-model="values" />
</template>
等待期间替换列表
外部换成内容不同的列表时,组件会使旧请求失效。底层稳定行标识仍支持组件自身编辑、插入和排序;本页额外的确认守卫更保守:列表、行内容或只读状态一旦变化,旧确认即作废,即使后来恢复原值也不放行。先确认删除,再进入可手动放行的模拟请求;替换整个列表也须明确确认移除原有全部行。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiButton, HuiDynamicInput, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
const values = ref(['原记录甲', '原记录乙'])
const waiting = ref<Array<() => void>>([])
let replaceAlive = true
let replaceRevision = 0
watch(
() => values.value,
() => replaceRevision++,
{ deep: true, flush: 'sync' }
)
onBeforeUnmount(() => {
replaceAlive = false
replaceRevision++
})
const replace = async () => {
const current = replaceRevision
if (!(await confirmReplace(0, values.value))) return
if (!replaceAlive || current !== replaceRevision) return
values.value = ['新记录甲', '新记录乙']
}
const release = () => {
waiting.value.shift()?.()
}
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const beforeRemove = createRemovalConfirmation(
() => values.value,
() => false,
() =>
new Promise<boolean>((resolve) => {
waiting.value.push(() => resolve(true))
})
)
const confirmReplace = createRemovalConfirmation(
() => [values.value],
() => false,
undefined,
() =>
`确定替换当前全部 ${values.value.length} 项吗?原有行及其全部字段将移除,并载入两条新示例记录。`
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiDynamicInput :before-remove="beforeRemove" v-model="values" />
<HuiSpace>
<HuiButton @click="replace">替换列表</HuiButton>
<HuiButton :disabled="!waiting.length" @click="release">放行最早的请求</HuiButton>
</HuiSpace>
<span>当前列表:{{ JSON.stringify(values) }};未返回请求:{{ waiting.length }}</span>
</HuiSpace>
</template>
先点击原记录的“-”,再替换列表,最后放行旧请求,新记录保持不变。取消只使组件忽略结果,不会中断业务请求本身。
排序
show-sort-button 在每行右侧加上移、下移按钮,第一行不能上移,最后一行不能下移。移动后焦点跟着这一行走,用键盘连续按回车可以一直移动。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
const steps = ref(['打开冰箱门', '把大象放进去', '关上冰箱门'])
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => steps.value,
() => false
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiDynamicInput :before-remove="confirmRemove0" v-model="steps" show-sort-button />
<span>顺序:{{ steps.join(' → ') }}</span>
</HuiSpace>
</template>
尺寸
size 可选 large、default、small,文本框和按钮的高度分别是 40、32、24px,和同尺寸的输入框、按钮一致。不传时跟随所在的 HuiFormItem、HuiForm,再没有就跟随 HuiConfigProvider。自定义行时用插槽参数 size 把尺寸传给行里的控件。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
const large = ref(['large'])
const normal = ref([{ key: 'size', value: 'default' }])
const small = ref(['small'])
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => large.value,
() => false
)
const confirmRemove1 = createRemovalConfirmation(
() => normal.value,
() => false
)
const confirmRemove2 = createRemovalConfirmation(
() => small.value,
() => false
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiDynamicInput
:before-remove="confirmRemove0"
v-model="large"
size="large"
show-sort-button
/>
<HuiDynamicInput
:before-remove="confirmRemove1"
v-model="normal"
preset="pair"
show-sort-button
/>
<HuiDynamicInput
:before-remove="confirmRemove2"
v-model="small"
size="small"
show-sort-button
/>
</HuiSpace>
</template>
禁用
disabled 后文本框和所有按钮都禁用,不能增删、移动,方法调用也不执行。放在禁用的 HuiForm 里也会禁用。自定义行时用插槽参数 disabled 禁用行里的控件。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiInput, HuiSpace, HuiSwitch, HuiMessageBox } from '@nscode/handy-ui'
const disabled = ref(true)
const tags = ref(['不能改', '也不能增删'])
const empty = ref<string[]>([])
const people = ref([{ name: '张三' }, { name: '李四' }])
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => tags.value,
() => disabled.value
)
const confirmRemove1 = createRemovalConfirmation(
() => empty.value,
() => disabled.value
)
const confirmRemove2 = createRemovalConfirmation(
() => people.value,
() => disabled.value
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSwitch v-model="disabled" active-text="禁用" />
<HuiDynamicInput
:before-remove="confirmRemove0"
v-model="tags"
:disabled="disabled"
show-sort-button
/>
<HuiDynamicInput :before-remove="confirmRemove1" v-model="empty" :disabled="disabled" />
<HuiDynamicInput
:before-remove="confirmRemove2"
v-model="people"
:disabled="disabled"
:on-create="() => ({ name: '' })"
>
<template #default="{ value, disabled: rowDisabled }">
<HuiInput v-model="value.name" :disabled="rowDisabled" placeholder="姓名" />
</template>
</HuiDynamicInput>
</HuiSpace>
</template>
在表单里校验
逐行校验
HuiFormItem 的 prop 支持数组路径,contacts.0.name 和 contacts[0].name 都可以。在插槽里给每个控件包一层 HuiFormItem,prop 按下标拼出路径,规则写在它的 rules 上(表单 rules 的键要和 prop 一字不差,动态的行不方便写在那里)。这样每一行单独校验、单独显示错误,validate() 返回的错误也按路径列出。
外层的 HuiFormItem 校验整个数组,下面用 required 要求至少一位联系人。整个组件是外层表单项的一个控件:值变化(包括行里的输入)时触发外层的 change 规则,焦点离开整个组件时触发 blur 规则,在行之间切换焦点不触发。
<script setup lang="ts">
import { reactive, ref, watch, onBeforeUnmount } from 'vue'
import {
HuiButton,
HuiDynamicInput,
HuiForm,
HuiFormItem,
HuiInput,
HuiSpace,
HuiMessageBox
} from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
interface Contact {
name: string
phone: string
}
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ contacts: [{ name: '', phone: '' }] as Contact[] })
const result = ref('')
const listRules: FormRule[] = [{ required: true, message: '至少添加 1 位联系人' }]
const nameRules: FormRule[] = [{ required: true, message: '请输入姓名', trigger: 'blur' }]
const phoneRules: FormRule[] = [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ pattern: /^1\d{10}$/, message: '手机号是 1 开头的 11 位数字', trigger: 'blur' }
]
const createContact = (): Contact => ({ name: '', phone: '' })
const submit = async () => {
const { valid, errors } = await formRef.value!.validate()
result.value = valid ? '校验通过' : `有错误的字段:${Object.keys(errors).join('、')}`
}
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => model.contacts,
() => false
)
</script>
<template>
<HuiForm ref="formRef" :model="model" @submit.prevent>
<HuiFormItem label="联系人" prop="contacts" :rules="listRules">
<HuiDynamicInput
:before-remove="confirmRemove0"
v-model="model.contacts"
:on-create="createContact"
show-sort-button
>
<template #default="{ value, index }">
<HuiFormItem :prop="`contacts.${index}.name`" :rules="nameRules" style="flex: 1">
<HuiInput v-model="value.name" placeholder="姓名" />
</HuiFormItem>
<HuiFormItem :prop="`contacts.${index}.phone`" :rules="phoneRules" style="flex: 1">
<HuiInput v-model="value.phone" placeholder="手机号" />
</HuiFormItem>
</template>
</HuiDynamicInput>
</HuiFormItem>
<HuiFormItem>
<HuiSpace wrap>
<HuiButton type="primary" @click="submit">提交</HuiButton>
<HuiButton @click="formRef?.clearValidate()">清除校验</HuiButton>
<span>{{ result }}</span>
</HuiSpace>
</HuiFormItem>
</HuiForm>
</template>
整体校验
只需要检查整个数组时(比如不能有空项、不能重复),把规则写在外层的 HuiFormItem 上,用 validator 拿到整个数组判断,行里不用再包 HuiFormItem。下面输入、增删时都会重新校验:
<script setup lang="ts">
import { reactive, ref, watch, onBeforeUnmount } from 'vue'
import {
HuiButton,
HuiDynamicInput,
HuiForm,
HuiFormItem,
HuiMessage,
HuiMessageBox
} from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ emails: ['admin@example.com', ''] })
const emailRules: FormRule[] = [
{ required: true, message: '至少填 1 个邮箱' },
{
validator: (_rule, value, callback) => {
const list = value as string[]
if (list.some((email) => !email.trim())) callback('有空着的邮箱')
else if (list.some((email) => !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))) {
callback('有邮箱格式不对')
} else if (new Set(list).size !== list.length) callback('邮箱不能重复')
else callback()
}
}
]
const submit = async () => {
const { valid } = await formRef.value!.validate()
if (valid) HuiMessage.success(`共 ${model.emails.length} 个邮箱,校验通过`)
}
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => model.emails,
() => false
)
</script>
<template>
<HuiForm ref="formRef" :model="model" @submit.prevent>
<HuiFormItem label="通知邮箱" prop="emails" :rules="emailRules">
<HuiDynamicInput
:before-remove="confirmRemove0"
v-model="model.emails"
:max="5"
placeholder="name@example.com"
/>
</HuiFormItem>
<HuiFormItem>
<HuiButton type="primary" @click="submit">提交</HuiButton>
</HuiFormItem>
</HuiForm>
</template>
事件
增删、移动时依次发出 update:modelValue 和 add、remove、move。只改行里的值时只发 update:modelValue。点下面的按钮看记录:
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiSpace, HuiMessageBox } from '@nscode/handy-ui'
const items = ref(['苹果', '香蕉'])
const logs = ref<string[]>([])
const log = (text: string) => {
logs.value = [text, ...logs.value].slice(0, 6)
}
const onAdd = (index: number, value: string) =>
log(`add:在第 ${index + 1} 行新增,初始值 ${JSON.stringify(value)}`)
const onRemove = (index: number, value: string) =>
log(`remove:删除第 ${index + 1} 行,值是 ${JSON.stringify(value)}`)
const onMove = (from: number, to: number) => log(`move:第 ${from + 1} 行移到第 ${to + 1} 行`)
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => items.value,
() => false
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiDynamicInput
:before-remove="confirmRemove0"
v-model="items"
show-sort-button
@add="onAdd"
@remove="onRemove"
@move="onMove"
/>
<span>绑定值:{{ items }}</span>
<div class="logs">
<div v-for="(item, i) in logs" :key="i">{{ item }}</div>
<div v-if="logs.length === 0">还没有事件</div>
</div>
</HuiSpace>
</template>
<style scoped>
.logs {
padding: var(--hui-spacing-2) var(--hui-spacing-3);
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
background: var(--hui-fill-color-light);
border-radius: var(--hui-border-radius);
}
</style>
无障碍和按钮文字
每个按钮都是原生 <button>,能用 Tab 聚焦、回车或空格触发,并带有“删除第 2 项”这样的无障碍名称,鼠标悬停时也显示这段文字。预设的文本框带“第 2 项”“第 2 项的键”这样的名称。
点按钮后焦点会放到合适的位置:插入后聚焦新行的第一个输入框;删除后聚焦顶上来的那一行的“-”按钮(删光了就聚焦“添加一项”);移动后焦点跟着这一行走。
labels 改这些文字,只传要改的几项,没传的项取语言包,{index} 会换成从 1 开始的行号。可改的项见下面的类型 DynamicInputLabels。把鼠标移到下面的按钮上看看:
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import { HuiDynamicInput, HuiMessageBox } from '@nscode/handy-ui'
const emails = ref(['a@example.com', 'b@example.com'])
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => emails.value,
() => false
)
</script>
<template>
<HuiDynamicInput
:before-remove="confirmRemove0"
v-model="emails"
show-sort-button
add-text="添加邮箱"
:labels="{
item: '第 {index} 个邮箱',
insert: '在第 {index} 个邮箱后添加',
remove: '删除第 {index} 个邮箱',
moveUp: '第 {index} 个邮箱上移',
moveDown: '第 {index} 个邮箱下移'
}"
/>
</template>
用方法操作
公开 remove(index) 不经过 beforeRemove。下面的用户删除按钮先调用与行内按钮相同的确认守卫,再调用真实方法;最少行数、只读、集合变化及卸载检查仍然生效。
通过 ref 调用 add、remove、move、focus。它们和点按钮一样受 min、max、禁用限制,没执行时返回 false;同样会发出 add、remove、move 事件。
<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from 'vue'
import {
HuiButton,
HuiDynamicInput,
HuiMessage,
HuiSpace,
HuiMessageBox,
HuiCheckbox,
HuiForm
} from '@nscode/handy-ui'
import type { DynamicInputExpose } from '@nscode/handy-ui'
const listRef = ref<DynamicInputExpose<string>>()
const items = ref(['第一项', '第二项', '第三项'])
const readonly = ref(false)
const addToTop = () => listRef.value?.add(0, `新的一项 ${items.value.length + 1}`)
let methodAlive = true
let methodRevision = 0
watch([() => items.value, () => readonly.value], () => methodRevision++, {
deep: true,
flush: 'sync'
})
onBeforeUnmount(() => {
methodAlive = false
methodRevision++
})
const removeLast = async () => {
if (readonly.value) return
if (items.value.length <= 1) {
HuiMessage.warning('至少保留 1 行')
return
}
const index = items.value.length - 1
const current = methodRevision
if (!(await confirmRemove0(index, items.value[index]))) return
if (!methodAlive || readonly.value || current !== methodRevision) return
if (!listRef.value?.remove(index)) HuiMessage.warning('至少保留 1 行')
}
const moveFirstToEnd = () => listRef.value?.move(0, items.value.length - 1)
const createRemovalConfirmation = <Row,>(
readRows: () => readonly Row[],
isReadonly: () => boolean = () => false,
afterConfirmation?: () => Promise<boolean>,
describe?: (index: number, value: Row) => string
) => {
let alive = true
let revision = 0
const pending = new Set<number>()
watch([readRows, isReadonly], () => revision++, { deep: true, flush: 'sync' })
onBeforeUnmount(() => {
alive = false
revision++
})
return async (index: number, value: Row) => {
if (
!alive ||
isReadonly() ||
pending.has(index) ||
!Number.isInteger(index) ||
index < 0 ||
index >= readRows().length ||
readRows()[index] !== value
)
return false
const current = revision
const valid = () => alive && !isReadonly() && current === revision
pending.add(index)
try {
const detail = value === '' || value == null ? '空行' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `确定删除第 ${index + 1} 项(${detail})吗?将移除此项及该项内的全部字段,其他行保持不变。`,
'删除动态录入项',
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
)
if (!valid()) return false
if (afterConfirmation && !(await afterConfirmation())) return false
return valid()
} catch {
return false
} finally {
pending.delete(index)
}
}
}
const confirmRemove0 = createRemovalConfirmation(
() => items.value,
() => readonly.value
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox class="dynamic-readonly" v-model="readonly">只读:禁止修改及删除</HuiCheckbox>
<HuiForm :model="{ items }" :readonly="readonly" @submit.prevent>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="addToTop">在开头插入</HuiButton>
<HuiButton @click="removeLast">删除最后一行</HuiButton>
<HuiButton @click="moveFirstToEnd">第一行移到最后</HuiButton>
<HuiButton @click="listRef?.focus(1)">聚焦第 2 行</HuiButton>
</HuiSpace>
<HuiDynamicInput :before-remove="confirmRemove0" ref="listRef" v-model="items" :min="1" />
</HuiSpace>
</HuiForm>
</HuiSpace>
</template>
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| modelValue | T[] | undefined | 绑定值,一项对应一行,支持 v-model 传入即受控,未传自行保存。 |
| preset | 'input' | 'pair' | 'input' | 内置的行内容:input 每行一个文本框(字符串数组),pair 每行键、值两个文本框({ key, value } 数组)。写了默认插槽时只决定新增行的默认值 |
| onCreate | (index: number) => T | — | 新增一行时调用,返回这一行的初始值,index 是新行的下标。不传时 input 是 '',pair 是 { key: '', value: '' } |
| min | number | 0 | 最少几行,行数等于它时“-”按钮禁用 |
| max | number | — | 最多几行,行数等于它时“+”按钮禁用;不传时不限制 |
| beforeRemove | (index: number, value: T) => boolean | void | Promise<boolean | void> | — | 按钮和插槽删除前的钩子,仅false、抛错或拒绝拦截;undefined放行,方法remove(index)不走它 |
| showSortButton | boolean | false | 显示上移、下移按钮 |
| size | 'large' | 'default' | 'small' | — | 尺寸。不传时跟随 FormItem、Form、ConfigProvider,都没有时是 default |
| disabled | boolean | false | 是否禁用。在禁用的表单里也会禁用 |
| placeholder | string | 随语言(中文:请输入) | input 预设文本框的占位文字 |
| keyPlaceholder | string | 随语言(中文:请输入键) | pair 预设键文本框的占位文字 |
| valuePlaceholder | string | 随语言(中文:请输入值) | pair 预设值文本框的占位文字 |
| addText | string | 随语言(中文:添加一项) | 一行都没有时显示的按钮文字 |
| labels | Partial<DynamicInputLabels> | — | 按钮和预设文本框的无障碍名称(按钮也用作悬停提示),只传要改的几项,没传的项取语言包,{index} 换成行号 |
| validateEvent | boolean | true | 值变化、焦点离开组件时是否触发所在表单项的校验 |
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| update:modelValue | (value: T[]) | 值变化时触发,参数是新数组(不会改原来的数组) |
| add | (index: number, value: T) | 新增一行后触发,index 是新行的下标,value 是它的初始值 |
| remove | (index: number, value: T) | 删除一行后触发,index 是被删行原来的下标,value 是它的值 |
| move | (from: number, to: number) | 移动一行后触发,从下标 from 移到 to |
Slots
| 插槽 | 参数 | 说明 |
|---|---|---|
| default | { value, index, update, remove, size, disabled } | 每一行的内容,写了以后不再显示预设的文本框。参数说明见类型 DynamicInputSlotProps |
方法
| 方法 | 参数 | 返回值 | 说明 |
|---|---|---|---|
| add | (index?: number, value?: T) | boolean | 在 index 处插入一行,不传时加在最后;value 不传时用 on-create 或预设的默认值 |
| remove | (index: number) | boolean | 删除第 index 行,不走 beforeRemove |
| move | (from: number, to: number) | boolean | 把第 from 行移到 to |
| focus | (index?: number) | — | 聚焦第 index 行(默认第 0 行)的第一个输入框;一行都没有时聚焦“添加一项”按钮 |
add、remove、move 受 min、max、禁用限制,下标越界或没执行时返回 false。
类型
import type {
DynamicInputSize,
DynamicInputPreset,
DynamicInputPair,
DynamicInputLabels,
DynamicInputProps,
DynamicInputEmits,
DynamicInputSlotProps,
DynamicInputExpose
} from '@nscode/handy-ui'
interface DynamicInputPair {
key: string
value: string
}
interface DynamicInputLabels {
insert: string // “+”按钮,默认取语言包(中文 '在第 {index} 项下方插入')
remove: string // “-”按钮,默认取语言包(中文 '删除第 {index} 项')
moveUp: string // 上移按钮,默认取语言包(中文 '上移第 {index} 项')
moveDown: string // 下移按钮,默认取语言包(中文 '下移第 {index} 项')
item: string // input 预设的文本框,默认取语言包(中文 '第 {index} 项')
key: string // pair 预设的键文本框,默认取语言包(中文 '第 {index} 项的键')
value: string // pair 预设的值文本框,默认取语言包(中文 '第 {index} 项的值')
}
interface DynamicInputSlotProps<T> {
value: T // 这一行的值
index: number // 这一行的下标,从 0 开始
update: (value: T) => void // 用新值替换这一行
remove: () => void // 删除这一行(受 min 和禁用限制)
size: DynamicInputSize // 组件当前的尺寸
disabled: boolean // 组件当前是否禁用
}