InputNumber 数字输入框
只能输入数字的输入框,带加减按钮。用来填数量、价格、百分比这类数值,可以限制范围、步长和小数位数。
引入
import { HuiInputNumber } from '@nscode/handy-ui'
自行保存与受控绑定
不传modelValue时内部保存,初始为空null;只监听更新仍是非受控,父组件无关重绘不会丢值。传了属性就受控(包括显式undefined/null),父拒绝或规范化回填后显示绑定值。中途增删绑定会给开发警告,按新模式取值。不新增defaultValue或valueOnClear。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInputNumber, HuiSpace } from '@nscode/handy-ui'
const redraw = ref(0)
const last = ref('尚未提交')
const record = (value: number | null) => {
last.value = value === null ? 'null' : String(value)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="redraw++">父组件重绘: {{ redraw }}</HuiButton>
<HuiInputNumber
:data-parent-render="redraw"
:min="0"
:max="5"
:precision="2"
placeholder="未绑定,自行保存"
@update:model-value="record"
/>
<span>最近提交: {{ last }}</span>
<HuiInputNumber :model-value="2" placeholder="固定受控值,父不回填" />
<HuiInputNumber :model-value="undefined" placeholder="显式undefined:受控空" />
<HuiInputNumber :model-value="null" placeholder="显式null:受控空" />
</HuiSpace>
</template>
基础用法
用 v-model 绑定一个数字。点两侧的加减按钮、聚焦后按上下键都可以加减一步;按住按钮超过 0.3 秒会连续加减。直接输入时,按回车或输入框失焦才提交,打字过程中不改绑定值。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber } from '@nscode/handy-ui'
const count = ref<number | null>(1)
</script>
<template>
<HuiInputNumber v-model="count" style="width: 200px" />
<p style="margin-top: 12px">绑定值:{{ count }}</p>
</template>
范围
min、max 限制取值范围。到达边界时对应的按钮变灰;输入超出范围的数字,提交时会被截到边界上。下面的范围是 1 到 10,点到 10 时加号变灰,输入 100 回车会变成 10。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber } from '@nscode/handy-ui'
const count = ref<number | null>(9)
</script>
<template>
<HuiInputNumber v-model="count" :min="1" :max="10" style="width: 200px" />
<p style="margin-top: 12px">绑定值:{{ count }}(范围 1 到 10)</p>
</template>
步长
step 是每次加减的量,可以是小数。加减时按“当前值和步长中较长的小数位数”取整,连点三次 0.1 得到的是 0.3,不会出现 0.30000000000000004。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber, HuiSpace } from '@nscode/handy-ui'
const count = ref<number | null>(0)
const ratio = ref<number | null>(0)
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">step = 5</span>
<HuiInputNumber v-model="count" :step="5" style="width: 200px" />
<span>{{ count }}</span>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">step = 0.1</span>
<HuiInputNumber v-model="ratio" :step="0.1" style="width: 200px" />
<span>{{ ratio }}</span>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 80px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
精度
precision 指定保留几位小数:显示时补齐位数(1.5 显示成 1.50),提交和加减的结果也四舍五入到这个位数。四舍五入按十进制算,1.005 保留两位是 1.01、2.675 是 2.68,不受二进制浮点误差影响。precision 为 0 时只能是整数,输入 2.6 回车会变成 3。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber, HuiSpace } from '@nscode/handy-ui'
const integer = ref<number | null>(2)
const price = ref<number | null>(1.5)
const rate = ref<number | null>(0.125)
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">precision = 0</span>
<HuiInputNumber v-model="integer" :precision="0" style="width: 200px" />
<span>绑定值:{{ integer }}</span>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">precision = 2</span>
<HuiInputNumber v-model="price" :precision="2" :step="0.1" style="width: 200px" />
<span>绑定值:{{ price }}</span>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">precision = 3</span>
<HuiInputNumber v-model="rate" :precision="3" :step="0.005" style="width: 200px" />
<span>绑定值:{{ rate }}</span>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 104px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
千分位与自定义显示
thousandSeparator 为 true 时用逗号分组,也可以传入 _、空格等分隔符。首帧和失焦时显示分组文字,聚焦时显示按 precision 补零的原始数字;打字期间不插入分隔符,不移动光标。粘贴带分组的文字后,在原生 change(回车或内容改变后的失焦)时移除配置的分隔符并提交数字。
formatter(value) 收到按 precision 舍入后的数字,返回的文字只用于失焦显示;配置它时不叠加自动千分位。提交时先移除千分位并解析普通十进制,失败后才调用 parser(text) 兜底;parser 收到去掉首尾空白的原始输入。因此只识别特定语法的 parser 不会拦住聚焦后的普通数字编辑。parser 返回有限数字后统一进行 min/max 限制和精度处理;返回 undefined、NaN、Infinity 等无效结果则恢复实际值。空输入绕过 parser,直接提交 null。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber, HuiSpace } from '@nscode/handy-ui'
const amount = ref<number | null>(1234567.8)
const custom = ref<number | null>(1234.5)
const formatted = ref<number | null>(1234.5)
const formatter = (value: number) =>
`数值 ${value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`
const parser = (text: string) => {
const raw = text.replace(/^数值\s*/, '').replaceAll(',', '')
return /^[+-]?(\d+(\.\d*)?|\.\d+)$/.test(raw) ? Number(raw) : undefined
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<span>逗号分组</span>
<HuiInputNumber v-model="amount" :precision="2" thousand-separator style="width: 260px" />
<code>{{ amount === null ? 'null' : amount }}</code>
</HuiSpace>
<HuiSpace wrap>
<span>自定义分隔符</span>
<HuiInputNumber v-model="custom" :precision="2" thousand-separator="_" style="width: 260px" />
<code>{{ custom === null ? 'null' : custom }}</code>
</HuiSpace>
<HuiSpace wrap>
<span>formatter / parser</span>
<HuiInputNumber
v-model="formatted"
:precision="2"
:formatter="formatter"
:parser="parser"
style="width: 260px"
/>
<code>{{ formatted === null ? 'null' : formatted }}</code>
</HuiSpace>
</HuiSpace>
</template>
自动分组使用 . 作为小数点,分隔符不能包含数字、.、+ 或 -;含这些字符时开发环境提示并忽略自动分组,避免剥离小数点或符号后改错数值。其他数字语法由 formatter/parser 成对处理。aria-valuenow 始终是实际数值,aria-valuetext 跟随当前显示文字。
单位前后缀
prefix / suffix 插槽显示独立单位,不拼进输入文字、不参与 parser。prefixIcon / suffixIcon 提供图标快捷写法,同名插槽优先;点单位会聚焦输入框,禁用时不聚焦。两侧按钮、右侧按钮和无按钮模式均可使用。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber, HuiSpace } from '@nscode/handy-ui'
const amount = ref<number | null>(1234.5)
const weight = ref<number | null>(25)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace v-for="size in ['large', 'default', 'small'] as const" :key="size" wrap>
<span>{{ size }}</span>
<HuiInputNumber
v-model="amount"
:size="size"
:precision="2"
thousand-separator
style="width: 260px"
>
<template #prefix>¥</template><template #suffix>元</template>
</HuiInputNumber>
<HuiInputNumber v-model="weight" :size="size" controls-position="right" style="width: 200px">
<template #suffix>kg</template>
</HuiInputNumber>
</HuiSpace>
<HuiSpace wrap>
<HuiInputNumber
v-model="weight"
:controls="false"
prefix-icon="search"
suffix-icon="check"
style="width: 200px"
/>
<HuiInputNumber v-model="weight" disabled style="width: 200px"
><template #suffix>kg</template></HuiInputNumber
>
</HuiSpace>
</HuiSpace>
</template>
空值
绑定值可以是 null 或显式 undefined,这时显示 placeholder。删光输入框内容后提交,统一请求 null;不会再请求 undefined。空值时点加减或按上下键,从 0 起算一步,再限制到 [min, max] 内,比如 min 是 3 时点加号得到 3。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInputNumber, HuiSpace } from '@nscode/handy-ui'
const count = ref<number | null>(null)
</script>
<template>
<HuiSpace wrap>
<HuiInputNumber v-model="count" :min="3" placeholder="请输入数量" style="width: 200px" />
<HuiButton @click="count = null">清空</HuiButton>
</HuiSpace>
<p style="margin-top: 12px">绑定值:{{ count === null ? 'null' : count }}</p>
</template>
尺寸
size 可选 large、default、small,高度分别是 40、32、24px,字号 16、14、12px,圆角 8、6、4px,和同尺寸的 HuiInput、HuiButton 一致。两侧的加减按钮是正方形,宽 40、32、24px,图标 18、16、14px;controls-position="right" 时右侧按钮宽 30、24、18px,上下两个按钮各占一半高,箭头 14、12、10px。放在 HuiForm 里且没传 size 时,跟随表单项或表单的尺寸。
下面每一行是一种尺寸:按钮在两侧、按钮在右侧,最后放一个同尺寸的按钮对比高度。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInputNumber, HuiSpace } from '@nscode/handy-ui'
const count = ref<number | null>(1)
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">large</span>
<HuiInputNumber v-model="count" size="large" style="width: 180px" />
<HuiInputNumber v-model="count" size="large" controls-position="right" style="width: 180px" />
<HuiButton size="large">按钮</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">default</span>
<HuiInputNumber v-model="count" style="width: 180px" />
<HuiInputNumber v-model="count" controls-position="right" style="width: 180px" />
<HuiButton>按钮</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">small</span>
<HuiInputNumber v-model="count" size="small" style="width: 180px" />
<HuiInputNumber v-model="count" size="small" controls-position="right" style="width: 180px" />
<HuiButton size="small">按钮</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
按钮位置
controls-position 可选 ''(默认,减号在左、加号在右)和 'right'(两个按钮上下叠放在右侧);:controls="false" 时不显示按钮,只能输入或用上下键。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber, HuiSpace } from '@nscode/handy-ui'
const count = ref<number | null>(1)
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">两侧('',默认)</span>
<HuiInputNumber v-model="count" style="width: 200px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">右侧(right)</span>
<HuiInputNumber v-model="count" controls-position="right" style="width: 200px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">不显示(controls 为 false)</span>
<HuiInputNumber v-model="count" :controls="false" style="width: 200px" />
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 184px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
禁用和只读
disabled 禁用后不能输入、不能加减;readonly 只读时可以聚焦、复制,但不能输入和加减,加减按钮也变灰。在禁用的 HuiForm 里也会被禁用。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber, HuiSpace } from '@nscode/handy-ui'
const count = ref<number | null>(1)
const empty = ref<number | null>(null)
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">disabled</span>
<HuiInputNumber v-model="count" disabled style="width: 180px" />
<HuiInputNumber v-model="count" controls-position="right" disabled style="width: 180px" />
<HuiInputNumber v-model="empty" placeholder="占位文字" disabled style="width: 180px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">readonly</span>
<HuiInputNumber v-model="count" readonly style="width: 180px" />
<HuiInputNumber v-model="count" controls-position="right" readonly style="width: 180px" />
<HuiInputNumber v-model="empty" placeholder="占位文字" readonly style="width: 180px" />
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 64px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
事件
change 和 update:modelValue 同时触发:点加减按钮、按上下键、长按连续加减时每变一次触发一次;直接输入时,回车或失焦提交、值有变化才触发。获得、失去焦点触发 focus、blur。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber } from '@nscode/handy-ui'
const count = ref<number | null>(1)
const logs = ref<string[]>([])
const log = (text: string) => {
logs.value = [text, ...logs.value].slice(0, 6)
}
const onChange = (value: number | null) => log(`change:${value}`)
</script>
<template>
<HuiInputNumber
v-model="count"
style="width: 200px"
@change="onChange"
@focus="log('focus')"
@blur="log('blur')"
/>
<p style="margin-top: 12px">最近的事件(新的在前):{{ logs.join(',') || '还没有' }}</p>
</template>
校验状态
数字输入框没有单独的状态属性,出错的样子由所在的 HuiFormItem 决定:校验不通过,或者给表单项传了 error 时,边框变成危险色,下面显示错误信息,内部的 <input> 带上 aria-invalid。
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiForm, HuiFormItem, HuiInputNumber, HuiSwitch } from '@nscode/handy-ui'
const showError = ref(true)
const model = reactive<{ count: number | null; price: number | null }>({ count: 0, price: null })
</script>
<template>
<HuiSwitch v-model="showError" active-text="显示错误" />
<HuiForm :model="model" label-width="80px" style="margin-top: 16px" @submit.prevent>
<HuiFormItem label="数量" :error="showError ? '数量至少是 1' : ''">
<HuiInputNumber v-model="model.count" style="width: 200px" />
</HuiFormItem>
<HuiFormItem label="单价" :error="showError ? '请填写单价' : ''">
<HuiInputNumber
v-model="model.price"
controls-position="right"
:precision="2"
placeholder="0.00"
style="width: 200px"
/>
</HuiFormItem>
</HuiForm>
</template>
调用方法
通过 ref 调用 focus()、blur(),或者用 inputRef 直接拿到内部的 <input> 元素。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInputNumber, HuiSpace } from '@nscode/handy-ui'
const numberRef = ref<InstanceType<typeof HuiInputNumber>>()
const count = ref<number | null>(128)
const focused = ref(false)
const selectAll = () => {
numberRef.value?.inputRef?.select()
}
</script>
<template>
<HuiInputNumber
ref="numberRef"
v-model="count"
style="width: 200px"
@focus="focused = true"
@blur="focused = false"
/>
<div style="margin-top: 12px">
<HuiSpace wrap>
<HuiButton @click="numberRef?.focus()">聚焦</HuiButton>
<HuiButton @click="numberRef?.blur()">失焦</HuiButton>
<HuiButton @click="selectAll">选中数字(inputRef)</HuiButton>
</HuiSpace>
</div>
<p style="margin-top: 12px">输入框{{ focused ? '已聚焦' : '没有聚焦' }}</p>
</template>
键盘操作
聚焦输入框后,按 ↑ 加一步,按 ↓ 减一步。加减按钮不在 Tab 顺序里(tabindex="-1"),键盘用户用上下键操作。输入框的 role 是 spinbutton,并带有 aria-valuenow、aria-valuemin、aria-valuemax(没设 min、max 时不输出)。
在表单里使用
放在 HuiFormItem 里时,值变化触发 change 规则,失焦触发 blur 规则;表单项的 label 会通过 for 关联到输入框。规则里的 min、max 对数字按数值比较。不需要校验时设 :validate-event="false"。
<script setup lang="ts">
import { reactive } from 'vue'
import { HuiForm, HuiFormItem, HuiInputNumber } from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const model = reactive<{ count: number | null }>({ count: null })
const rules: Record<string, FormRule[]> = {
count: [
{ required: true, message: '请填写数量', trigger: 'change' },
{ min: 1, max: 99, message: '数量在 1 到 99 之间', trigger: 'change' }
]
}
</script>
<template>
<HuiForm :model="model" :rules="rules" @submit.prevent>
<HuiFormItem label="数量" prop="count">
<HuiInputNumber v-model="model.count" />
</HuiFormItem>
</HuiForm>
</template>
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| modelValue | number | null | undefined | 传入即受控;未传内部初始null;显式undefined/null显示为空 |
| min | number | -Infinity | 最小值 |
| max | number | Infinity | 最大值 |
| step | number | 1 | 每次加减的步长 |
| precision | number | - | 保留几位小数。不传时不格式化 |
| thousandSeparator | boolean | string | false | 失焦千分位;true用逗号,字符串按字面分组,不能含数字、点或正负号 |
| formatter | (value: number) => string | — | 失焦显示格式,参数按precision舍入;优先于自动千分位 |
| parser | (text: string) => number | undefined | — | 普通十进制解析失败后的兜底;无效结果恢复实际值,空输入直接null |
| prefixIcon | string | — | 前缀图标,prefix插槽优先 |
| suffixIcon | string | — | 后缀图标,suffix插槽优先 |
| disabled | boolean | false | 是否禁用 |
| readonly | boolean | false | 是否只读 |
| controls | boolean | true | 是否显示加减按钮 |
| controlsPosition | '' | 'right' | '' | 加减按钮的位置:'' 是左右两侧,'right' 是都放在右侧 |
| size | 'large' | 'default' | 'small' | - | 尺寸。不传时跟随表单,不在表单里时是 'default' |
| placeholder | string | - | 占位文字 |
| validateEvent | boolean | true | 值变化和失焦时是否触发所在表单项的校验 |
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| update:modelValue | (value: number | null) | 提交了新值时触发:按回车、内容有变化时失焦、点加减按钮、按上下键、长按连续加减。值没变时不触发 |
| change | (value: number | null) | 和 update:modelValue 同时触发,时机相同 |
| focus | (event: FocusEvent) | 获得焦点时触发 |
| blur | (event: FocusEvent) | 失去焦点时触发 |
Slots
| 名称 | 说明 |
|---|---|
| prefix | 数字前的单位或图标,独立于输入文本;覆盖prefixIcon |
| suffix | 数字后的单位或图标,独立于输入文本;覆盖suffixIcon |
方法
| 名称 | 类型 | 说明 |
|---|---|---|
| focus | () => void | 让输入框获得焦点 |
| blur | () => void | 让输入框失去焦点 |
| inputRef | HTMLInputElement | 内部的 input 元素 |
类型
import type { InputNumberProps, InputNumberEmits, InputNumberSize } from '@nscode/handy-ui'
type InputNumberSize = 'large' | 'default' | 'small'
interface InputNumberProps {
modelValue?: number | null
min?: number
max?: number
step?: number
precision?: number
thousandSeparator?: boolean | string
formatter?: (value: number) => string
parser?: (text: string) => number | undefined
prefixIcon?: string
suffixIcon?: string
disabled?: boolean
readonly?: boolean
controls?: boolean
controlsPosition?: '' | 'right'
size?: InputNumberSize
placeholder?: string
validateEvent?: boolean
}
interface InputNumberEmits {
'update:modelValue': [value: number | null]
change: [value: number | null]
focus: [event: FocusEvent]
blur: [event: FocusEvent]
}
焦点方法与公开类型
组件ref使用InputNumberExpose。focus()聚焦当前、已选或首个可用控件,不改值、不打开文件选择框;禁用或卸载后不聚焦,只读按控件原合同保留可聚焦性。blur()只让本组件所属文档内的活动元素失焦,不影响外部焦点。组控件的focus/blur只在整组进出时各触发一次,内部移动不重复;既有表单校验行为保持。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { InputNumberExpose } from '@nscode/handy-ui'
const control = ref<InputNumberExpose>()
const value = ref(1)
const event = ref('等待操作')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @mousedown.prevent @click="control?.focus()">focus()</HuiButton>
<HuiButton @mousedown.prevent @click="control?.blur()">blur()</HuiButton>
</HuiSpace>
<HuiInputNumber ref="control" v-model="value" @focus="event = 'focus'" @blur="event = 'blur'" />
<span>{{ event }}</span>
</HuiSpace>
</template>
| 方法 | 签名 |
|---|---|
| focus | () => void |
| blur | () => void |