Appearance
numeric 数值工具
normalizeNumber 是一个纯函数,用于对任意字符串形式的数值进行过滤、限制正负、控制小数位并裁剪到指定范围,可在 input、blur 或数据落库前统一处理,替代原先的 v-numeric 指令。
导入
ts
import {
normalizeNumber,
type NormalizeNumberOptions
} from '@cuixingjian/cui-utils'使用场景
输入时限制正/负、小数位
vue
<script setup lang="ts">
import { ref } from 'vue'
import {
normalizeNumber,
type NormalizeNumberOptions
} from '@cuixingjian/cui-utils'
const value = ref('')
const options: NormalizeNumberOptions = {
allowNegative: false,
decimalPlaces: 2
}
function handleInput(event: Event) {
const target = event.target as HTMLInputElement
const nextValue = normalizeNumber(target.value, options)
const caret = target.selectionStart ?? nextValue.length
target.value = nextValue
target.setSelectionRange(caret, caret)
value.value = nextValue
}
</script>
<template>
<input :value="value" @input="handleInput" placeholder="最多 2 位小数" />
</template>失焦时裁剪范围
vue
<script setup lang="ts">
import { ref } from 'vue'
import { normalizeNumber } from '@cuixingjian/cui-utils'
const amount = ref('')
const options = { min: 0, max: 9999, decimalPlaces: 2 }
function handleBlur(event: FocusEvent) {
const target = event.target as HTMLInputElement
const normalized = normalizeNumber(target.value, options)
target.value = normalized
amount.value = normalized
}
</script>
<template>
<input :value="amount" @blur="handleBlur" placeholder="0 ~ 9999" />
</template>数据入库前的最终裁剪
ts
import { normalizeNumber } from '@cuixingjian/cui-utils'
const payload = {
price: normalizeNumber(userInput, { min: 0, decimalPlaces: 2 })
}API
normalizeNumber(value, options?)
- 作用:过滤非法字符、限制正负、小数位,并在给定范围内裁剪。
- 返回:
string
NormalizeNumberOptions
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
allowNegative | boolean | true | 是否允许负数 |
allowDecimal | boolean | true | 是否允许小数 |
decimalPlaces | number | null | null | 限制小数位;null 不限制 |
min | number | string | undefined | 最小值(会自动转换为数字) |
max | number | string | undefined | 最大值 |
提示:
normalizeNumber为纯函数,可在任何框架中独立调用。