DynamicInput
Edits a list with a variable number of rows. Each row has + and − controls for insertion and removal, with optional up/down controls for ordering. Use it for URLs, request parameters, contacts and similar lists.
Every removal on this page, including empty rows, requires confirmation. Cancel, closing and Esc preserve data. List changes, row edits, read-only changes and unmounting invalidate outstanding confirmations. The public remove method does not invoke beforeRemove automatically, so user buttons must first reuse the same confirmation guard.
Import
import { HuiDynamicInput } from '@nscode/handy-ui'
Internal State and Controlled Updates
Without modelValue, or with only an update listener, rows are stored internally from an empty array. Supplying the prop, including undefined, makes the component controlled. A rejected request leaves the parent list unchanged. Adding, editing, moving and removing retain stable row keys. Requests within one batch are merged; later batches read the actual state. Internal object rows support direct slot property edits. Switching control modes cancels older pending removal hooks.
<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('No request yet')
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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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++">Parent redraw {{ q1Redraw }}</HuiButton
><HuiSpace direction="vertical" fill>
<div>
<p>Prop omitted; internal state</p>
<div class="q1-local">
<HuiDynamicInput
:before-remove="confirmRemove0"
@update:model-value="q1LocalRows = $event"
:max="3"
show-sort-button
/>
</div>
</div>
<div>
<p>Update listener only; still internal state</p>
<div class="q1-listener">
<HuiDynamicInput
:before-remove="confirmRemove1"
:max="3"
show-sort-button
@update:model-value="recordListenerRows"
/>
</div>
</div>
<div>
<p>Explicit undefined; parent value takes precedence</p>
<div class="q1-empty">
<HuiDynamicInput
:before-remove="confirmRemove2"
:max="3"
show-sort-button
:model-value="undefined"
/>
</div>
</div>
<div>
<p>Fixed controlled value; parent rejects updates</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>Two-way binding</p>
<div class="q1-bound">
<HuiDynamicInput
:before-remove="confirmRemove4"
:max="3"
show-sort-button
v-model="q1Model"
/>
</div>
</div>
<p class="q1-notification">
Bound value: {{ q1Model }}; latest request: {{ q1Last }}
</p></HuiSpace
>
</div>
</template>
Basic Usage
V-model binds an array, with one item per row. The default input preset provides one text input per row and uses a string array. A row's + inserts an empty row below it; − requests removal of that row after confirmation.
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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="Enter a city" />
<span>Bound value: {{ cities }}</span>
</HuiSpace>
</template>
Key-Value Pairs
Preset=pair provides two inputs per row and binds an array of { key, value } objects, useful for request parameters, headers and environment variables. Key-placeholder and value-placeholder customize their placeholders. Editing the key or value replaces only those fields; other row properties, such as id, remain intact.
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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>Request parameters: {{ params }}</span>
<HuiDynamicInput
:before-remove="confirmRemove1"
v-model="headers"
preset="pair"
key-placeholder="Header name"
value-placeholder="Header value"
/>
<span>Request headers: {{ headers }}</span>
</HuiSpace>
</template>
Custom Rows
When the presets are insufficient, render each row through the default slot:
- Value is the row value; index is its zero-based position.
- Update(newValue) replaces the row.
- Remove() requests row removal, subject to min and disabled restrictions.
- Size and disabled report the component state; pass them to row controls so they follow it.
Provide on-create for custom rows. It receives the new index and returns the initial value. Return a new object each time rather than sharing one among rows.
The contact example contains name, mobile and relationship fields. Since rows are objects, v-model=value.name can edit a property directly. Controls are arranged horizontally with automatic gaps. Inputs fill remaining width, while Select has an explicit width.
<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: 'Parent', value: 'parent' },
{ label: 'Spouse', value: 'spouse' },
{ label: 'Child', value: 'child' },
{ label: 'Friend', 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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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="Name"
:aria-label="`Name of contact ${index + 1}`"
/>
<HuiInput
v-model="value.phone"
placeholder="Mobile"
:aria-label="`Mobile of contact ${index + 1}`"
/>
<HuiSelect
v-model="value.relation"
:options="relations"
placeholder="Relationship"
:aria-label="`Relationship of contact ${index + 1}`"
style="width: 120px; flex: none"
/>
</template>
</HuiDynamicInput>
<span>Bound value: {{ contacts }}</span>
</HuiSpace>
</template>
Primitive rows, such as numbers or strings, cannot be edited through object properties. Replace the whole row through update. Each row below uses a numeric input:
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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="`Price ${index + 1}`"
style="flex: 1"
@update:model-value="update"
/>
</template>
</HuiDynamicInput>
<span>Bound value: {{ prices }}, total {{ total() }} currency units</span>
</HuiSpace>
</template>
Empty State and Text
An empty list shows a dashed Add item button. Add-text customizes its label. Placeholder changes the input preset's placeholder.
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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="Add URL"
placeholder="https://"
/>
<span>URLs: {{ sites }}</span>
</HuiSpace>
</template>
Minimum and Maximum Rows
Min disables − when the row count reaches the minimum. Max disables all + controls when the maximum is reached. Min defaults to 0; max is unlimited when omitted. The component does not automatically fill the list to min, so supply enough initial rows if needed.
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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 (currently {{ upToThree.length }} items): </span>
<HuiDynamicInput :before-remove="confirmRemove1" v-model="upToThree" :max="3" />
</HuiSpace>
</template>
Confirmation Before Removal
BeforeRemove lets the application decide whether removal is allowed. This example confirms both populated and empty rows. False, throws or rejections block; undefined allows. Cancel, closing and Esc return false. Repeated attempts on the same row do not open another confirmation, while other rows can request separately. The guard observes list and row changes synchronously and rejects stale results.
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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>
Replacing the List While Waiting
The component invalidates an old request when an external list has different content. Its stable row identity still supports its own editing, insertion and ordering. This page's additional confirmation guard is stricter: any list, row-content or read-only change invalidates the confirmation, even if reverted later. First confirm removal, then enter the manually released simulated request. Replacing the entire list also requires confirming removal of every existing row.
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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,
() =>
`Replace all ${values.value.length} current items? This removes every existing row and its fields, then loads two new sample records.`
)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiDynamicInput :before-remove="beforeRemove" v-model="values" />
<HuiSpace>
<HuiButton @click="replace">Replace list</HuiButton>
<HuiButton :disabled="!waiting.length" @click="release"
>Release the earliest request</HuiButton
>
</HuiSpace>
<span>Current list: {{ JSON.stringify(values) }}; pending requests: {{ waiting.length }}</span>
</HuiSpace>
</template>
Request removal of an original row and confirm, then replace the list and confirm its full scope. Releasing the older request leaves new rows unchanged. Cancellation makes the component ignore results without aborting the underlying request.
Sorting
Show-sort-button adds up/down controls. The first row cannot move up, and the last cannot move down. Focus follows the moved row, allowing repeated Enter presses to continue moving it.
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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>Order: {{ steps.join(' → ') }}</span>
</HuiSpace>
</template>
Sizes
Size accepts large, default or small, with input/button heights of 40, 32 and 24px. Omitted size follows HuiFormItem, HuiForm and HuiConfigProvider. For custom rows, pass the slot's size to its controls.
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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
Disabled prevents input and all add/remove/move controls, including method calls. A disabled enclosing HuiForm also disables the component. For custom rows, pass the slot's disabled state to its controls.
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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="Disabled" />
<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="Name" />
</template>
</HuiDynamicInput>
</HuiSpace>
</template>
Form Validation
Per-Row Validation
HuiFormItem prop supports array paths such as contacts.0.name and contacts[0].name. Wrap each slot control in HuiFormItem, build its path from the index and put rules on that item. Form-level rule keys must exactly match prop, making local rules more convenient for dynamic rows. Each row validates and shows errors separately; validate() reports errors by path.
The outer form item validates the array itself; required below demands at least one contact. The whole DynamicInput is one control for that item. Value changes, including edits inside object rows, trigger its change rules. Focus leaving the entire component triggers blur; moving between rows does not.
<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: 'Add at least one contact' }]
const nameRules: FormRule[] = [{ required: true, message: 'Enter a name', trigger: 'blur' }]
const phoneRules: FormRule[] = [
{ required: true, message: 'Enter a mobile number', trigger: 'blur' },
{
pattern: /^1\d{10}$/,
message: 'The mobile number must have 11 digits starting with 1',
trigger: 'blur'
}
]
const createContact = (): Contact => ({ name: '', phone: '' })
const submit = async () => {
const { valid, errors } = await formRef.value!.validate()
result.value = valid
? 'Validation passed'
: `Fields with errors: ${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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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="Contacts" 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="Name" />
</HuiFormItem>
<HuiFormItem :prop="`contacts.${index}.phone`" :rules="phoneRules" style="flex: 1">
<HuiInput v-model="value.phone" placeholder="Mobile" />
</HuiFormItem>
</template>
</HuiDynamicInput>
</HuiFormItem>
<HuiFormItem>
<HuiSpace wrap>
<HuiButton type="primary" @click="submit">Submit</HuiButton>
<HuiButton @click="formRef?.clearValidate()">Clear validation</HuiButton>
<span>{{ result }}</span>
</HuiSpace>
</HuiFormItem>
</HuiForm>
</template>
Whole-List Validation
For rules about the entire array, such as no empty items or duplicates, put a validator on the outer HuiFormItem and inspect the whole array. Individual rows need no form-item wrappers. The following revalidates on input, addition and removal:
<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: 'Enter at least one email address' },
{
validator: (_rule, value, callback) => {
const list = value as string[]
if (list.some((email) => !email.trim())) callback('Some email addresses are empty')
else if (list.some((email) => !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))) {
callback('Some email addresses are invalid')
} else if (new Set(list).size !== list.length) callback('Email addresses must be unique')
else callback()
}
}
]
const submit = async () => {
const { valid } = await formRef.value!.validate()
if (valid) HuiMessage.success(`${model.emails.length} email addresses; validation passed`)
}
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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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="Notification Emails" 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">Submit</HuiButton>
</HuiFormItem>
</HuiForm>
</template>
Events
Adding, removing and moving emit update:modelValue followed by add, remove or move. Editing a row value emits only update:modelValue. Interact below to inspect the log:
<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: inserted row ${index + 1}, initial value ${JSON.stringify(value)}`)
const onRemove = (index: number, value: string) =>
log(`remove: removed row ${index + 1}, value ${JSON.stringify(value)}`)
const onMove = (from: number, to: number) => log(`move: row ${from + 1} moved to row ${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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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>Bound value: {{ items }}</span>
<div class="logs">
<div v-for="(item, i) in logs" :key="i">{{ item }}</div>
<div v-if="logs.length === 0">No events yet</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>
Accessibility and Button Labels
Each action is a native button supporting Tab, Enter and Space, with an accessible name such as Remove item 2, also shown on hover. Preset inputs have names such as Item 2 and Key for item 2.
Focus moves appropriately: insertion focuses the new row's first input; removal focuses the next row's − control, or Add item if empty; reordering keeps focus with the row.
Labels overrides these strings. Supply only the needed keys; omitted keys use the locale. {index} becomes the one-based row number. See DynamicInputLabels under Types. Hover over the controls below to compare:
<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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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="Add email"
:labels="{
item: 'Email {index}',
insert: 'Insert after email {index}',
remove: 'Remove email {index}',
moveUp: 'Move email {index} up',
moveDown: 'Move email {index} down'
}"
/>
</template>
Using Methods
The public remove(index) method bypasses beforeRemove. The example's removal button first calls the same guard used by row controls, then the real method. Minimum rows, read-only state, list changes and unmounting still apply.
Call add, remove, move and focus through a ref. They respect min, max and disabled restrictions like the controls, return false when no operation occurs, and emit the corresponding add/remove/move events.
<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('Keep at least 1 row')
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('Keep at least 1 row')
}
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 ? 'Empty row' : JSON.stringify(value)
await HuiMessageBox.confirm(
describe
? describe(index, value)
: `Remove item ${index + 1} (${detail})? This removes this row and all its fields. Other rows remain unchanged.`,
'Remove a dynamic input item',
{ type: 'warning', confirmButtonText: 'Remove', cancelButtonText: 'Cancel' }
)
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"
>Read only: prevent editing and removal</HuiCheckbox
>
<HuiForm :model="{ items }" :readonly="readonly" @submit.prevent>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="addToTop">Insert at the beginning</HuiButton>
<HuiButton @click="removeLast">Remove the last row</HuiButton>
<HuiButton @click="moveFirstToEnd">Move the first row to the end</HuiButton>
<HuiButton @click="listRef?.focus(1)">Focus row 2</HuiButton>
</HuiSpace>
<HuiDynamicInput :before-remove="confirmRemove0" ref="listRef" v-model="items" :min="1" />
</HuiSpace>
</HuiForm>
</HuiSpace>
</template>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| modelValue | T[] | undefined | One value per row, supporting v-model. Controlled when supplied, otherwise internally stored |
| preset | 'input' | 'pair' | 'input' | Input provides a text field per string row; pair provides key/value inputs per object row. With a default slot, determines only the default value of new rows |
| onCreate | (index: number) => T | — | Returns a new row's initial value for its index. Defaults to '' for input and { key: '', value: '' } for pair |
| min | number | 0 | Minimum rows; − is disabled at the limit |
| max | number | — | Maximum rows; + is disabled at the limit. Unlimited when omitted |
| beforeRemove | (index: number, value: T) => boolean | void | Promise<boolean | void> | — | Check before button/slot removal. False, throws or rejections block; undefined allows. Public remove(index) bypasses it |
| showSortButton | boolean | false | Whether to show up/down controls |
| size | 'large' | 'default' | 'small' | — | Follows FormItem, Form and ConfigProvider, then default |
| disabled | boolean | false | Disabled state; also follows a disabled form |
| placeholder | string | Localized input prompt | Input preset placeholder |
| keyPlaceholder | string | Localized key prompt | Pair key placeholder |
| valuePlaceholder | string | Localized value prompt | Pair value placeholder |
| addText | string | Localized Add item | Button text when the list is empty |
| labels | Partial<DynamicInputLabels> | — | Accessible names for buttons and preset inputs, also used for button hover text. Omitted keys use the locale; {index} becomes the row number |
| validateEvent | boolean | true | Whether value changes and focus leaving the component trigger form-item validation |
Events
| Event | Callback Arguments | Description |
|---|---|---|
| update:modelValue | (value: T[]) | Value changes, with a new array rather than mutating the original array |
| add | (index: number, value: T) | After insertion, with the new index and initial value |
| remove | (index: number, value: T) | After removal, with the former index and removed value |
| move | (from: number, to: number) | After moving from one index to another |
Slots
| Slot | Arguments | Description |
|---|---|---|
| default | { value, index, update, remove, size, disabled } | Row content, replacing preset inputs. See DynamicInputSlotProps |
Methods
| Method | Arguments | Return Value | Description |
|---|---|---|---|
| add | (index?: number, value?: T) | boolean | Inserts at index, or appends when omitted. Without value, uses on-create or the preset default |
| remove | (index: number) | boolean | Removes row index without invoking beforeRemove |
| move | (from: number, to: number) | boolean | Moves a row from one index to another |
| focus | (index?: number) | — | Focuses the first input in the row, defaulting to row 0. An empty list focuses Add item |
Add, remove and move respect min, max and disabled. Invalid indices or an operation not performed return false.
Types
import type {
DynamicInputSize,
DynamicInputPreset,
DynamicInputPair,
DynamicInputLabels,
DynamicInputProps,
DynamicInputEmits,
DynamicInputSlotProps,
DynamicInputExpose
} from '@nscode/handy-ui'
interface DynamicInputPair {
key: string
value: string
}
interface DynamicInputLabels {
insert: string // Insert button; defaults to the active locale's insert-after-item label
remove: string // Remove button; defaults to the active locale's remove-item label
moveUp: string // Move-up button; defaults to the active locale's move-item-up label
moveDown: string // Move-down button; defaults to the active locale's move-item-down label
item: string // Input preset field; defaults to the active locale's item label
key: string // Pair key field; defaults to the active locale's item-key label
value: string // Pair value field; defaults to the active locale's item-value label
}
interface DynamicInputSlotProps<T> {
value: T // This row's value
index: number // Zero-based index of this row
update: (value: T) => void // Replace this row with a new value
remove: () => void // Request row removal, subject to min and disabled restrictions
size: DynamicInputSize // Current component size
disabled: boolean // Whether the component is currently disabled
}