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 在每行右側加上移、下移按鈕,第一行不能上移,最後一行不能下移。移動後焦點跟著這一行走,用鍵盤連續按 Enter可以一直移動。
<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 聚焦、Enter 或空白觸發,並帶有“刪除第 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 // 元件目前是否禁用
}