Input 输入框
单行文本输入框,用来输入用户名、搜索词、金额这类短文本。支持清空、密码显示切换、密码强度提示、字数统计、前后缀图标和插槽、前置和后置内容,放在 HuiForm 里时会跟随表单的禁用、尺寸并触发校验。多行文本用 HuiTextarea。
引入
import { HuiInput } from '@nscode/handy-ui'
自行保存与受控绑定
不传 modelValue 时,组件自行保存输入,父组件无关重绘不会清空;只监听 update:modelValue 也属于此模式。传了属性就受控,包括显式 undefined、null(都显示为空);父组件不回填时仍显示原绑定值。不提供 defaultValue。中途增删绑定属性会给出开发警告,以切换后的模式为准。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInput, HuiSpace } from '@nscode/handy-ui'
const redraw = ref(0)
const lastInput = ref('尚未输入')
const record = (value: string | number) => {
lastInput.value = String(value)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="redraw++">父组件重绘:{{ redraw }}</HuiButton>
<HuiInput
:data-parent-render="redraw"
clearable
:maxlength="20"
show-word-limit
placeholder="自行保存,仅监听更新"
@update:model-value="record"
/>
<span>最近更新:{{ lastInput }}</span>
<HuiInput model-value="固定值" placeholder="受控:父组件不回填" />
<HuiInput :model-value="undefined" placeholder="显式 undefined:受控空值" />
<HuiInput :model-value="null" placeholder="显式 null:受控空值" />
</HuiSpace>
</template>
基础用法
用 v-model 绑定一个字符串,placeholder 是没有内容时显示的占位文字。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput } from '@nscode/handy-ui'
const value = ref('')
</script>
<template>
<HuiInput v-model="value" placeholder="请输入内容" />
<p style="margin-top: 12px">输入的内容:{{ value || '(空)' }}</p>
</template>
只允许输入某些字符
allow-input 的六个预设和正则会逐字符过滤,粘贴时只留下符合规则的字符;函数判断输入后的整个值,返回 false 时恢复原值和选区。空字符串始终允许,不会调用函数,因此能够删空。
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiInput, HuiSpace } from '@nscode/handy-ui'
import type { InputAllowPreset } from '@nscode/handy-ui'
const presets: InputAllowPreset[] = ['digit', 'int', 'num', 'alpha', 'alnum', 'hex']
const values = reactive<Record<InputAllowPreset, string>>({
digit: '',
int: '',
num: '',
alpha: '',
alnum: '',
hex: ''
})
const patternValue = ref('')
const decimalValue = ref('')
const allowDecimal = (value: string) => /^\d*(\.\d{0,2})?$/.test(value)
</script>
<template>
<HuiSpace wrap align="start">
<div v-for="preset in presets" :key="preset" style="width: 180px">
<p>{{ preset }}</p>
<HuiInput v-model="values[preset]" :allow-input="preset" :placeholder="preset" />
<p>绑定值:'{{ values[preset] }}'</p>
</div>
<div style="width: 180px">
<p>正则:数字和小数点</p>
<HuiInput v-model="patternValue" :allow-input="/[\d.]/" placeholder="逐字符过滤" />
<p>绑定值:'{{ patternValue }}'</p>
</div>
<div style="width: 180px">
<p>函数:最多两位小数</p>
<HuiInput v-model="decimalValue" :allow-input="allowDecimal" placeholder="整个值校验" />
<p>绑定值:'{{ decimalValue }}'</p>
</div>
</HuiSpace>
</template>
digit 只允许 0-9;int 另外允许开头一个负号;num 再允许一个小数点,输入中的 -、.、-. 也保留;alpha 只允许英文字母;alnum 允许英文字母和数字;hex 允许 0-9、A-F、a-f。
digit 默认使用 inputmode="numeric",num 使用 inputmode="decimal";int 不强制键盘类型,便于输入负号。只要正整数并希望弹出数字键盘时用 digit。显式传入的 inputmode 优先。过滤覆盖打字、粘贴、拖放和输入法上屏,外部传入的绑定值不会被过滤。HuiInput 的函数接收整个值,HuiInputOtp 的函数接收单个字符。
已有小数点时,中间再输入或粘贴的小数点会被过滤,原有小数点和负号保留;选中它们后可以替换。未启用掩码时,allow-input 和 maxlength 同用会先过滤插入内容和已有前后文,再按过滤后前后文的 UTF-16 长度计算剩余容量,不拆开 emoji 等完整码位。有有效编辑区间时,只截断本次插入段,保留未编辑的有效前后文;删除不会连带截断原值。设不设 maxlength,编辑时都会过滤外部值中的无效字符;外部回填本身不主动过滤。没有有效快照的自动填充等整值更新才截断整个值。函数仍先检查整个候选值,通过后再限制插入长度。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace } from '@nscode/handy-ui'
const amount = ref('12.5')
const code = ref('')
const full = ref('123')
const replacement = ref('1234')
</script>
<template>
<HuiSpace direction="vertical" fill>
<p>在 1 后输入小数点,原有的 12.5 保持不变</p>
<HuiInput v-model="amount" allow-input="num" />
<span>金额:'{{ amount }}'</span>
<p>粘贴 a1b2c3,先过滤得到 123,再限制为三位</p>
<HuiInput v-model="code" allow-input="digit" :maxlength="3" show-word-limit />
<span>代码:'{{ code }}'</span>
<p>三位已满:在开头输入 9 仍为 123,可选中原字符后替换</p>
<HuiInput v-model="full" allow-input="digit" :maxlength="3" show-word-limit />
<span>保留未编辑部分:'{{ full }}'</span>
<p>四位已满:在 1 后粘贴 99 仍为 1234;选中 23 再粘贴 a9b8c7 得到 1984</p>
<HuiInput v-model="replacement" allow-input="digit" :maxlength="4" show-word-limit />
<span>替换结果:'{{ replacement }}'</span>
</HuiSpace>
</template>
输入掩码
mask 用 9 表示数字、a 表示英文字母、* 表示英文字母或数字,反斜线转义下一个字符,? 后面的部分可以不填。只在 type="text"、type="tel" 时生效;中间分隔符在后面有内容时补上,对应段填满后补上闭合字面量,例如 (99) 显示为 (12)。
默认 mask-value="raw",绑定值不带前缀和分隔符;masked 则带格式。必填部分从未填满变成填满时触发 finish,继续输入可选段不会重复触发。外部回填不会触发 finish。
单码位 insertText 或输入法上屏的单个字符按原始可填字符处理,避免误删与字面量相同的输入。一次插入多个字符、拖放、输入法整串上屏、粘贴或替换输入,会先去掉当前槽位对应的字面量前缀和分隔符。例如一次插入或拖入 +8613800000000,显示 +86 138 0000 0000,raw 值为 13800000000;前缀数字不会计入号码或 finish 参数。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace, HuiMessage } from '@nscode/handy-ui'
const phone = ref('')
const card = ref('')
const prefixed = ref('')
const formatted = ref('')
const closed = ref('')
const finished = (value: string) => HuiMessage.success(`已填满:${value}`)
</script>
<template>
<HuiSpace wrap align="start">
<div style="width: 220px">
<p>手机号(raw)</p>
<HuiInput
v-model="phone"
mask="999 9999 9999"
placeholder="138 0000 0000"
@finish="finished"
/>
<p>绑定值:'{{ phone }}'</p>
</div>
<div style="width: 220px">
<p>银行卡(16 位必填,后三位可选)</p>
<HuiInput
v-model="card"
mask="9999 9999 9999 9999? 999"
placeholder="16 或 19 位"
@finish="finished"
/>
<p>绑定值:'{{ card }}'</p>
</div>
<div style="width: 220px">
<p>带字面量前缀:粘贴、拖入或键盘整串插入 +8613800000000</p>
<HuiInput
v-model="prefixed"
mask="+86 999 9999 9999"
allow-input="digit"
type="tel"
placeholder="+86 138 0000 0000"
@finish="finished"
/>
<p>绑定值:'{{ prefixed }}'</p>
</div>
<div style="width: 220px">
<p>手机号(masked)</p>
<HuiInput
v-model="formatted"
mask="999 9999 9999"
mask-value="masked"
placeholder="包含分隔符"
@finish="finished"
/>
<p>绑定值:'{{ formatted }}'</p>
</div>
<div style="width: 220px">
<p>尾部字面量(masked)</p>
<HuiInput v-model="closed" mask="(99)" mask-value="masked" @finish="finished" />
<p>填满两位后绑定值带括号:'{{ closed }}'</p>
</div>
</HuiSpace>
</template>
自定义掩码占位符
mask-tokens 扩展或覆盖占位符。下面用 X 限定统一社会信用代码允许的字符;正则即使带 g、y 标志也不会在连续输入时丢字符。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace } from '@nscode/handy-ui'
const value = ref('')
const tokens = { X: /[0-9A-HJ-NPQRTUWXY]/ }
const escaped = ref('')
const escapedMask = '\\9aa-99'
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput
v-model="value"
mask="XXXXXXXXXXXXXXXXXX"
:mask-tokens="tokens"
placeholder="18 位统一社会信用代码"
/>
<span>绑定值:'{{ value }}'</span>
<HuiInput v-model="escaped" :mask="escapedMask" placeholder="字面量 9 + 两位字母 + 两位数字" />
<span>转义前缀 9 不包含在 raw 绑定中:'{{ escaped }}'</span>
</HuiSpace>
</template>
掩码表单校验
未填完时失焦会保留内容,是否允许提交由表单决定。isMaskComplete 支持 raw 和 masked 值,也支持传入自定义占位符。从字面量段的开头匹配前缀或分隔符,不要求完整格式,例如 '+861'、'+86 1' 对 '+86 999' 都不算填满。粘贴或自动填充 +8613800000000、+86-138-0000-0000、13800000000 都得到同一个号码。纯数字字面量可能与 raw 值重合:'99' 对 '\\999' 会被视为字面量 9 加一个有效数字;这类情况请传完整显示值(如 '999')消除歧义。
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
HuiForm,
HuiFormItem,
HuiInput,
HuiButton,
HuiMessage,
isMaskComplete
} from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ phone: '' })
const mask = '999 9999 9999'
const rules: Record<string, FormRule[]> = {
phone: [
{
validator: (_rule, value) => isMaskComplete(String(value ?? ''), mask),
message: '请填满 11 位手机号',
trigger: 'blur'
}
]
}
const submit = async () => {
if ((await formRef.value!.validate()).valid) HuiMessage.success(`手机号:${model.phone}`)
}
</script>
<template>
<HuiForm ref="formRef" :model="model" :rules="rules" label-width="80px" @submit.prevent>
<HuiFormItem label="手机号" prop="phone">
<HuiInput v-model="model.phone" :mask="mask" placeholder="138 0000 0000" />
</HuiFormItem>
<HuiFormItem><HuiButton type="primary" @click="submit">校验并提交</HuiButton></HuiFormItem>
</HuiForm>
</template>
尺寸
size 可选 large、default、small,高度分别是 40、32、24px,字号 16、14、12px,圆角 8、6、4px,和同尺寸的 HuiButton 一致。prefix-icon、suffix-icon 的图标和清空、显示密码按钮的图标比文字大 2px(18、16、14px),前后缀插槽里自己放的图标不受影响。放在 HuiForm 里且没传 size 时,跟随表单项或表单的尺寸。
下面每一行是一种尺寸:带前缀图标的可清空输入框、带显示密码按钮的密码框,最后放一个同尺寸的按钮对比高度。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInput, HuiSpace } from '@nscode/handy-ui'
const keyword = ref('输入框')
const password = ref('123456')
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">large</span>
<HuiInput
v-model="keyword"
size="large"
prefix-icon="search"
clearable
style="width: 200px"
/>
<HuiInput
v-model="password"
size="large"
type="password"
show-password
style="width: 200px"
/>
<HuiButton size="large">按钮</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">default</span>
<HuiInput v-model="keyword" prefix-icon="search" clearable style="width: 200px" />
<HuiInput v-model="password" type="password" show-password style="width: 200px" />
<HuiButton>按钮</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">small</span>
<HuiInput
v-model="keyword"
size="small"
prefix-icon="search"
clearable
style="width: 200px"
/>
<HuiInput
v-model="password"
size="small"
type="password"
show-password
style="width: 200px"
/>
<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>
禁用和只读
disabled 禁用后不能编辑,也不能聚焦;readonly 只读时可以聚焦、选中和复制文字,但不能修改。两种状态下都不显示清空按钮和密码切换按钮。在禁用的 HuiForm 里也会被禁用。
下面第一行是禁用、第二行是只读,从左到右是有内容、没有内容(显示占位文字)、可清空的密码框:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace } from '@nscode/handy-ui'
const value = ref('不能修改的内容')
const empty = ref('')
const password = ref('123456')
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">disabled</span>
<HuiInput v-model="value" prefix-icon="user" disabled style="width: 200px" />
<HuiInput v-model="empty" placeholder="禁用时的占位文字" disabled style="width: 200px" />
<HuiInput
v-model="password"
type="password"
show-password
clearable
disabled
style="width: 200px"
/>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">readonly</span>
<HuiInput v-model="value" prefix-icon="user" readonly style="width: 200px" />
<HuiInput v-model="empty" placeholder="只读时的占位文字" readonly style="width: 200px" />
<HuiInput
v-model="password"
type="password"
show-password
clearable
readonly
style="width: 200px"
/>
</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>
可清空
clearable 为 true 且有内容时,右侧显示清空按钮。点它会把值清成 '',依次触发 update:modelValue、input、clear、change,然后让输入框重新获得焦点。清空按钮是一个带“清空”名称的 <button>,可以用 Tab 聚焦、回车触发。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiMessage } from '@nscode/handy-ui'
const value = ref('点右侧按钮清空')
const onClear = () => {
HuiMessage.info('已清空')
}
</script>
<template>
<HuiInput v-model="value" clearable @clear="onClear" />
</template>
密码框
type="password" 时输入的内容显示成圆点。再加上 show-password,右侧会出现眼睛按钮,点击在明文和密文之间切换;不加时没有切换按钮,只能看到圆点。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace } from '@nscode/handy-ui'
const password = ref('123456')
const confirm = ref('')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput v-model="password" type="password" placeholder="不带切换按钮" />
<HuiInput v-model="confirm" type="password" show-password placeholder="带显示密码按钮" />
</HuiSpace>
</template>
密码强度
type="password" 时加上 show-strength,输入框下方显示一条分三段的强度条和文字:弱(点亮一段,危险色)、中(两段,警告色)、强(三段,成功色)。没有输入内容时不显示;显示时输入框下面让出一行的位置,在表单里错误提示会跟着下移。
默认规则(getPasswordStrength):少于 8 位是弱;8 位及以上按包含的字符种类计分,小写字母、大写字母、数字、符号各算 1 分,12 位及以上再加 1 分,1 分弱、2 分中、3 分及以上强。
强度变化时读屏软件会读出“密码强度: 中”这样的提示,输入框也通过 aria-describedby 关联到强度,聚焦时一起读出。
下面第一个输入框可以自己输入试试,后面三个分别是弱、中、强的例子(点眼睛按钮看明文):
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace } from '@nscode/handy-ui'
const password = ref('')
const weak = ref('12345678')
const medium = ref('abcd1234')
const strong = ref('Abcd1234!')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput
v-model="password"
type="password"
show-password
show-strength
placeholder="输入密码看强度"
/>
<HuiInput v-model="weak" type="password" show-password show-strength />
<HuiInput v-model="medium" type="password" show-password show-strength />
<HuiInput v-model="strong" type="password" show-password show-strength />
</HuiSpace>
</template>
自定义强度规则
strength-method 传一个函数自定义规则:参数是输入的密码(不会是空字符串),返回 'weak'、'medium'、'strong' 之一。返回其他值时不显示强度,开发环境下会在控制台警告。
只想在默认规则上加一点限制时,可以从 @nscode/handy-ui 导入 getPasswordStrength 接着用。下面第一个输入框是完全自定义的规则,第二个在默认规则的基础上把常见的弱密码一律算成弱:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace, getPasswordStrength } from '@nscode/handy-ui'
import type { InputPasswordStrength } from '@nscode/handy-ui'
const custom = ref('')
const extended = ref('Password123')
// 少于 10 位是弱;10 位及以上,同时有字母和数字是中,再加上符号是强
const customRule = (value: string): InputPasswordStrength => {
if (value.length < 10 || !/[a-zA-Z]/.test(value) || !/\d/.test(value)) return 'weak'
return /[^a-zA-Z\d]/.test(value) ? 'strong' : 'medium'
}
// 默认规则,另外带 password、123456、qwerty 字样的一律算弱
const extendedRule = (value: string): InputPasswordStrength =>
/password|123456|qwerty/i.test(value) ? 'weak' : getPasswordStrength(value)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput
v-model="custom"
type="password"
show-password
show-strength
:strength-method="customRule"
placeholder="至少 10 位,字母、数字、符号都有才是强"
/>
<HuiInput
v-model="extended"
type="password"
show-password
show-strength
:strength-method="extendedRule"
placeholder="带 password、123456 的算弱"
/>
</HuiSpace>
</template>
强度文字
strength-texts 依次传弱、中、强三档的文字,没传的项取语言包(中文是“弱”“中”“强”)。strength-label 是读屏软件在强度前面读出的说明,默认取语言包(中文“密码强度”),界面上不显示;传空字符串时只读强度文字。只改这一处时用这两个属性,整个应用切换语言见《国际化》。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace } from '@nscode/handy-ui'
const password = ref('abcd1234')
const texts = ['Too weak', 'Fair', 'Strong']
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput
v-model="password"
type="password"
show-password
show-strength
:strength-texts="texts"
strength-label="Password strength"
placeholder="Password"
/>
</HuiSpace>
</template>
在表单里校验强度
强度提示只是提示,不会拦住提交。要求密码至少达到“中”时,在校验规则里用 getPasswordStrength(或者你自己的规则函数)判断。强度显示在输入框下面,校验不通过时错误提示排在强度下面:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
HuiButton,
HuiForm,
HuiFormItem,
HuiInput,
HuiMessage,
getPasswordStrength
} from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ password: 'abc' })
const rules: Record<string, FormRule[]> = {
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{
validator: (_rule, value) => getPasswordStrength(String(value ?? '')) !== 'weak',
message: '密码太弱,至少 8 位,并包含字母、数字、符号中的两种以上',
trigger: 'blur'
}
]
}
const submit = async () => {
const { valid } = await formRef.value!.validate()
if (valid) HuiMessage.success('提交成功')
}
</script>
<template>
<HuiForm ref="formRef" :model="model" :rules="rules" label-width="80px" @submit.prevent>
<HuiFormItem label="新密码" prop="password">
<HuiInput v-model="model.password" type="password" show-password show-strength />
</HuiFormItem>
<HuiFormItem>
<HuiButton type="primary" @click="submit">提交</HuiButton>
</HuiFormItem>
</HuiForm>
</template>
前后缀图标
prefix-icon、suffix-icon 传图标名,图标分别显示在输入框左侧和右侧,只用来装饰,不能点击。两个可以同时用。能用的图标名见 Icon 组件的文档。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace } from '@nscode/handy-ui'
const keyword = ref('')
const title = ref('')
const phone = ref('')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput v-model="keyword" prefix-icon="search" placeholder="前缀图标(prefix-icon)" />
<HuiInput v-model="title" suffix-icon="edit" placeholder="后缀图标(suffix-icon)" />
<HuiInput v-model="phone" prefix-icon="phone" suffix-icon="lock" placeholder="前后都有" />
</HuiSpace>
</template>
前缀、后缀插槽
需要放文字或自定义内容时用 prefix、suffix 插槽,插槽内容优先于 prefix-icon、suffix-icon。显示清空按钮或密码切换按钮时,后缀(插槽和图标)会让出位置,不显示:下面第三个输入框有内容时显示清空按钮,清空后才显示后缀“.com”。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiIcon, HuiSpace } from '@nscode/handy-ui'
const price = ref('')
const user = ref('')
const site = ref('example')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput v-model="price" placeholder="金额">
<template #prefix>¥</template>
<template #suffix>元</template>
</HuiInput>
<HuiInput v-model="user" placeholder="用户名">
<template #prefix><HuiIcon name="user" /></template>
</HuiInput>
<HuiInput v-model="site" clearable placeholder="域名">
<template #prefix>https://</template>
<template #suffix>.com</template>
</HuiInput>
</HuiSpace>
</template>
前置、后置内容
prepend、append 插槽的内容放在输入区外侧:和输入框共用一圈边框,中间用一条竖线隔开,带浅灰底色,只有两端是圆角。常用来放协议、域名后缀、单位这类固定文字。
和前缀、后缀的区别:prefix、suffix 在输入区里面,没有底色和竖线。两组可以同时用,也能和清空按钮、字数统计一起用;有内容时清空按钮只让后缀让位,后置内容一直显示。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiIcon, HuiInput, HuiSpace } from '@nscode/handy-ui'
const site = ref('example')
const receiver = ref('')
const subdomain = ref('docs')
const link = ref('')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput v-model="site" clearable placeholder="域名">
<template #prepend>https://</template>
<template #append>.com</template>
</HuiInput>
<HuiInput v-model="receiver" prefix-icon="mail" placeholder="和前缀图标一起用">
<template #prepend>收件人</template>
</HuiInput>
<HuiInput v-model="subdomain" :maxlength="20" show-word-limit clearable>
<template #append>.example.com</template>
</HuiInput>
<HuiInput v-model="link" placeholder="前置里放图标">
<template #prepend><HuiIcon name="link" /></template>
</HuiInput>
</HuiSpace>
</template>
前置、后置放按钮和选择器
插槽里直接放 HuiButton、HuiSelect 时,前置、后置区不再有底色和内边距,按钮、选择器自己的边框顶替输入框那一段的边框,接缝处只有一条线,外侧的圆角和输入框一致、里侧是直角。
- 选择器默认按内容宽,写
style="width: ..."固定宽度,切换选项时输入框才不会忽宽忽窄。 - 按钮、选择器的高度会撑满输入框,字号、内边距仍按它们自己的
size,输入框是large、small时给它们传同样的size。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInput, HuiMessage, HuiSelect, HuiSpace } from '@nscode/handy-ui'
const keyword = ref('')
const host = ref('')
const protocol = ref('https://')
const suffix = ref('.com')
const amount = ref('100')
const protocols = [
{ label: 'http://', value: 'http://' },
{ label: 'https://', value: 'https://' }
]
const suffixes = [
{ label: '.com', value: '.com' },
{ label: '.cn', value: '.cn' },
{ label: '.org', value: '.org' }
]
const search = () => {
HuiMessage.info(keyword.value ? `搜索:${keyword.value}` : '请输入关键词')
}
const visit = () => {
HuiMessage.info(`访问:${protocol.value}${host.value || 'example'}${suffix.value}`)
}
const step = (delta: number) => {
amount.value = String((Number(amount.value) || 0) + delta)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput
v-model="keyword"
clearable
placeholder="输入后按回车或点搜索"
@keydown.enter="search"
>
<template #append>
<HuiButton type="primary" icon="search" @click="search">搜索</HuiButton>
</template>
</HuiInput>
<HuiInput v-model="host" placeholder="example">
<template #prepend>
<HuiSelect v-model="protocol" :options="protocols" style="width: 100px" />
</template>
<template #append>
<HuiSelect v-model="suffix" :options="suffixes" style="width: 90px" />
</template>
</HuiInput>
<HuiInput v-model="amount" placeholder="数量">
<template #prepend>
<HuiButton icon="minus" aria-label="减 10" @click="step(-10)" />
</template>
<template #append>
<HuiButton icon="plus" aria-label="加 10" @click="step(10)" />
</template>
</HuiInput>
<HuiInput v-model="host" placeholder="example">
<template #prepend>https://</template>
<template #append>
<HuiButton @click="visit">访问</HuiButton>
</template>
</HuiInput>
</HuiSpace>
</template>
前置、后置内容的尺寸和禁用
前置、后置内容跟着输入框的 size 变:文字的字号、左右内边距和输入框一样,三种尺寸都对齐。输入框禁用时,前置、后置的文字变成禁用色;里面放的按钮、选择器是独立的组件,要自己加 disabled。
<script setup lang="ts">
import { reactive } from 'vue'
import { HuiButton, HuiInput, HuiSelect, HuiSpace } from '@nscode/handy-ui'
const sizes = ['large', 'default', 'small'] as const
const hosts = reactive({ large: 'example', default: 'example', small: 'example' })
const protocols = reactive({ large: 'https://', default: 'https://', small: 'https://' })
const options = [
{ label: 'http://', value: 'http://' },
{ label: 'https://', value: 'https://' }
]
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace v-for="size in sizes" :key="size" wrap>
<span class="row-label">{{ size }}</span>
<HuiInput v-model="hosts[size]" :size="size" style="width: 260px">
<template #prepend>https://</template>
<template #append>.com</template>
</HuiInput>
<HuiInput v-model="hosts[size]" :size="size" clearable style="width: 340px">
<template #prepend>
<HuiSelect
v-model="protocols[size]"
:options="options"
:size="size"
style="width: 120px"
/>
</template>
<template #append>
<HuiButton type="primary" :size="size">访问</HuiButton>
</template>
</HuiInput>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">disabled</span>
<HuiInput model-value="example" disabled style="width: 260px">
<template #prepend>https://</template>
<template #append>.com</template>
</HuiInput>
<HuiInput model-value="example" disabled style="width: 340px">
<template #prepend>
<HuiSelect model-value="https://" :options="options" disabled style="width: 120px" />
</template>
<template #append>
<HuiButton type="primary" disabled>访问</HuiButton>
</template>
</HuiInput>
</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>
前置、后置内容的校验状态
在出错的 HuiFormItem 里,整圈边框(包括前置、后置区)变成危险色;里面放的选择器也一起变红,按钮保持自己的颜色。用开关切换表单项的 error 看看:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
HuiButton,
HuiForm,
HuiFormItem,
HuiInput,
HuiSelect,
HuiSpace,
HuiSwitch
} from '@nscode/handy-ui'
const showError = ref(true)
const model = reactive({ host: 'exa mple', protocol: 'https://', keyword: '', price: '-1' })
const protocols = [
{ label: 'http://', value: 'http://' },
{ label: 'https://', value: 'https://' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSwitch v-model="showError" active-text="显示错误" />
<HuiForm :model="model" label-width="80px" @submit.prevent>
<HuiFormItem label="网址" :error="showError ? '网址里不能有空格' : ''">
<HuiInput v-model="model.host" clearable>
<template #prepend>
<HuiSelect v-model="model.protocol" :options="protocols" style="width: 100px" />
</template>
<template #append>.com</template>
</HuiInput>
</HuiFormItem>
<HuiFormItem label="关键词" :error="showError ? '请输入关键词' : ''" size="large">
<HuiInput v-model="model.keyword" prefix-icon="search">
<template #append>
<HuiButton type="primary" size="large">搜索</HuiButton>
</template>
</HuiInput>
</HuiFormItem>
<HuiFormItem label="价格" :error="showError ? '价格不能小于 0' : ''" size="small">
<HuiInput v-model="model.price">
<template #prepend>¥</template>
<template #append>元</template>
</HuiInput>
</HuiFormItem>
</HuiForm>
</HuiSpace>
</template>
字数统计
同时设置 maxlength 和 show-word-limit,右侧显示“已输入/上限”。只设 maxlength 时只限制长度,不显示统计;只设 show-word-limit 不起作用。字数统计和清空按钮可以同时显示,三种尺寸都能用。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiSpace } from '@nscode/handy-ui'
const limitOnly = ref('')
const withCount = ref('')
const small = ref('小尺寸')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput v-model="limitOnly" :maxlength="10" placeholder="最多 10 个字,不显示统计" />
<HuiInput
v-model="withCount"
:maxlength="20"
show-word-limit
clearable
placeholder="最多 20 个字"
/>
<HuiInput v-model="small" size="small" :maxlength="20" show-word-limit />
</HuiSpace>
</template>
输入类型
type 可选 text、password、number、email、tel、url,对应原生 input 的类型,会影响手机上弹出的键盘。type="number" 时 v-model 拿到的仍然是字符串(如 "12"),需要数字时写 v-model.number;要限制范围、步长时用 HuiInputNumber。
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiInput, HuiSpace } from '@nscode/handy-ui'
const form = reactive({ text: '', password: '', email: '', tel: '', url: '' })
const age = ref<number | string>('')
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">text</span>
<HuiInput v-model="form.text" placeholder="普通文本(默认)" style="width: 240px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">password</span>
<HuiInput v-model="form.password" type="password" placeholder="密码" style="width: 240px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">number</span>
<HuiInput v-model.number="age" type="number" placeholder="年龄" style="width: 240px" />
<span>值:{{ age === '' ? '(空)' : age }},类型:{{ typeof age }}</span>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">email</span>
<HuiInput v-model="form.email" type="email" placeholder="邮箱" style="width: 240px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">tel</span>
<HuiInput v-model="form.tel" type="tel" placeholder="手机号" style="width: 240px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">url</span>
<HuiInput v-model="form.url" type="url" placeholder="网址" style="width: 240px" />
</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>
事件
输入时触发 input(和 update:modelValue 同时),内容有变化后失焦或按回车触发 change,获得、失去焦点触发 focus、blur,点清空按钮触发 clear。在下面的输入框里打字、按回车、点外面、点清空按钮,看看事件的顺序:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput } from '@nscode/handy-ui'
const value = ref('')
const logs = ref<string[]>([])
const log = (text: string) => {
logs.value = [text, ...logs.value].slice(0, 6)
}
const onInput = (val: string | number) => log(`input:${val}`)
const onChange = (val: string | number) => log(`change:${val}`)
</script>
<template>
<HuiInput
v-model="value"
clearable
placeholder="输入几个字试试"
@input="onInput"
@change="onChange"
@focus="log('focus')"
@blur="log('blur')"
@clear="log('clear')"
/>
<p style="margin-top: 12px">最近的事件(新的在前):{{ logs.join(',') || '还没有' }}</p>
</template>
校验状态
输入框没有单独的状态属性,出错的样子由所在的 HuiFormItem 决定:校验不通过,或者给表单项传了 error 时,输入框的边框变成危险色,下面显示错误信息,内部的 <input> 带上 aria-invalid。下面用开关切换表单项的 error,三种尺寸都一样:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiForm, HuiFormItem, HuiInput, HuiSwitch } from '@nscode/handy-ui'
const showError = ref(true)
const model = reactive({ username: 'admin', email: 'abc', phone: '123' })
</script>
<template>
<HuiSwitch v-model="showError" active-text="显示错误" />
<HuiForm :model="model" label-width="80px" style="margin-top: 16px" @submit.prevent>
<HuiFormItem label="用户名" :error="showError ? '用户名已被占用' : ''" size="large">
<HuiInput v-model="model.username" prefix-icon="user" clearable />
</HuiFormItem>
<HuiFormItem label="邮箱" :error="showError ? '邮箱格式不正确' : ''">
<HuiInput v-model="model.email" prefix-icon="mail" />
</HuiFormItem>
<HuiFormItem label="手机号" :error="showError ? '请输入 11 位手机号' : ''" size="small">
<HuiInput v-model="model.phone" :maxlength="11" show-word-limit />
</HuiFormItem>
</HuiForm>
</template>
原生属性和事件
组件上写的 class、style 留在最外层的容器上。data-hui-field、data-invalid、data-disabled、data-open、data-filled 是保留的边框状态标记,落在带边框的根容器,客户端与SSR一致。其余属性和监听仍透传到内部的 <input>:name、id、autofocus、tabindex、aria-label、其他 data-*,以及 @keydown、@keyup、@paste 等组件没有声明的事件。autocomplete 是原生的自动填充属性,例如写 'off' 关掉浏览器的历史记录提示。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiMessage } from '@nscode/handy-ui'
const keyword = ref('')
const search = () => {
HuiMessage.info(`搜索:${keyword.value}`)
}
</script>
<template>
<HuiInput
v-model="keyword"
name="keyword"
autocomplete="off"
aria-label="搜索关键词"
placeholder="输入后按回车搜索"
class="search-box"
@keydown.enter="search"
/>
</template>
调用方法
通过 ref 调用 focus()、blur()、select()、clear(),或者用 inputRef 直接拿到内部的 <input> 元素。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiButton, HuiSpace } from '@nscode/handy-ui'
const inputRef = ref<InstanceType<typeof HuiInput>>()
const value = ref('一段文字')
const focused = ref(false)
const moveToEnd = () => {
const el = inputRef.value?.inputRef
if (!el) return
el.focus()
el.setSelectionRange(el.value.length, el.value.length)
}
</script>
<template>
<HuiInput ref="inputRef" v-model="value" @focus="focused = true" @blur="focused = false" />
<div style="margin-top: 12px">
<HuiSpace wrap>
<HuiButton @click="inputRef?.focus()">聚焦</HuiButton>
<HuiButton @click="inputRef?.blur()">失焦</HuiButton>
<HuiButton @click="inputRef?.select()">全选</HuiButton>
<HuiButton @click="inputRef?.clear()">清空</HuiButton>
<HuiButton @click="moveToEnd">光标移到末尾(inputRef)</HuiButton>
</HuiSpace>
</div>
<p style="margin-top: 12px">输入框{{ focused ? '已聚焦' : '没有聚焦' }}</p>
</template>
在表单里使用
放在 HuiFormItem 里时,值变化触发 change 规则,失焦触发 blur 规则;表单项的 label 会通过 for 关联到输入框,校验出错时输入框带上 aria-invalid 和指向错误提示的 aria-describedby。不需要校验时设 :validate-event="false"。
<script setup lang="ts">
import { reactive } from 'vue'
import { HuiForm, HuiFormItem, HuiInput } from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const model = reactive({ username: '' })
const rules: Record<string, FormRule[]> = {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 3, max: 12, message: '长度 3 到 12 个字符', trigger: 'change' }
]
}
</script>
<template>
<HuiForm :model="model" :rules="rules" @submit.prevent>
<HuiFormItem label="用户名" prop="username">
<HuiInput v-model="model.username" />
</HuiFormItem>
</HuiForm>
</template>
祖先变量覆盖
--hui-input-padding-x 控制输入区左右内边距,尺寸默认仍为 large 16px、default 12px、small 8px。变量可以设在输入框自身或任意祖先;下例外层统一为 20px,内层局部改为 8px,各组件仍保持自己的高度、字号和圆角。
前置、后置内容使用同一个内边距;存在附加内容的一侧由附加内容提供边距,输入框外层该侧保持 0,文本与分隔线之间的补偿同步更新。附加按钮或选择器仍沿用原来的贴边布局。仅覆盖变量即可,无需选择内部节点;父组件的 <style scoped> 可直接在祖先类上设置变量,不需要 :deep()。
<script setup lang="ts">
import { reactive } from 'vue'
import { HuiInput } from '@nscode/handy-ui'
const values = reactive({
small: '小尺寸',
normal: '附加内容',
large: '大尺寸',
nested: '局部覆盖'
})
</script>
<template>
<div
class="input-variables-demo"
style="--hui-input-padding-x:20px;display:flex;flex-direction:column;gap:var(--hui-spacing-4);max-width:440px"
>
<HuiInput v-model="values.small" size="small"><template #prefix>前缀</template></HuiInput>
<HuiInput v-model="values.normal"
><template #prepend>https://</template><template #append>.com</template></HuiInput
>
<HuiInput v-model="values.large" size="large"><template #suffix>后缀</template></HuiInput>
<div class="input-variables-nested" style="--hui-input-padding-x:8px">
<HuiInput v-model="values.nested" />
</div>
<span class="input-variables-value">当前输入:{{ values.normal }}</span>
</div>
</template>
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| modelValue | string | number | null | undefined | 传入即受控;未传自行保存,初始为空字符串;显式 null/undefined 显示为空 |
| type | 'text' | 'password' | 'number' | 'email' | 'tel' | 'url' | 'text' | 原生 input 的类型 |
| size | 'large' | 'default' | 'small' | - | 尺寸。不传时跟随表单,不在表单里时是 'default' |
| placeholder | string | - | 占位文字 |
| disabled | boolean | false | 是否禁用 |
| readonly | boolean | false | 是否只读 |
| clearable | boolean | false | 有内容时是否显示清空按钮 |
| showPassword | boolean | false | type 为 password 时是否显示“显示 / 隐藏密码”按钮 |
| maxlength | number | - | 最大输入长度 |
| minlength | number | - | 最小输入长度。原生属性,只在原生表单校验时起作用,不影响 HuiForm |
| showWordLimit | boolean | false | 是否显示字数统计,需要同时设置 maxlength |
| prefixIcon | string | - | 前缀图标名 |
| suffixIcon | string | - | 后缀图标名 |
| autocomplete | string | - | 原生 autocomplete 属性,例如 'off'、'username' |
| form | string | - | 原生 form 属性:输入框所属 <form> 的 id |
| allowInput | InputAllowInput | - | 预设或正则逐字符过滤;函数判断整个输入值,返回 false 时撤销输入。空字符串始终允许 |
| mask | string | - | 输入格式,9 数字、a 字母、* 字母或数字,反斜线转义,? 后可选。仅 text、tel 生效 |
| maskTokens | Record<string, RegExp> | - | 扩展或覆盖占位符 |
| maskValue | 'raw' | 'masked' | 'raw' | 绑定值不带格式,或包含前缀和分隔符 |
| validateEvent | boolean | true | 值变化和失焦时是否触发所在表单项的校验 |
| showStrength | boolean | false | type 为 password 时,在输入框下方显示密码强度(强度条和文字)。没有输入内容时不显示 |
| strengthMethod | (value: string) => InputPasswordStrength | - | 自定义强度规则,参数是输入的密码(不为空),返回 'weak'、'medium'、'strong'。不传时用 getPasswordStrength |
| strengthTexts | string[] | 随语言(中文:['弱', '中', '强']) | 弱、中、强三档显示的文字,依次传三项,没传的项取语言包 |
| strengthLabel | string | 随语言(中文:密码强度) | 读屏软件在强度文字前读出的说明,界面上不显示。传空字符串时不读 |
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| update:modelValue | (value: string | number) | 输入时触发,参数是输入框里的字符串。输入法组合期间不触发,上屏后触发一次 |
| input | (value: string | number) | 和 update:modelValue 同时触发 |
| change | (value: string | number) | 原生 change:内容有变化后失焦或按回车时触发;点清空按钮时也触发,参数是 '' |
| focus | (event: FocusEvent) | 获得焦点时触发 |
| blur | (event: FocusEvent) | 失去焦点时触发 |
| clear | - | 点清空按钮或调用 clear() 后触发 |
| finish | (value: string) | 掩码必填部分从未填满变为填满时触发,参数遵循 maskValue;外部回填不触发 |
Slots
| 插槽 | 作用域参数 | 说明 |
|---|---|---|
| prefix | - | 输入框左侧的内容,优先于 prefixIcon |
| suffix | - | 输入框右侧的内容,优先于 suffixIcon。显示清空、密码切换按钮时不显示 |
| prepend | - | 输入区外侧左边的内容,和输入框共用边框。放 HuiButton、HuiSelect 时边框自动合并 |
| append | - | 输入区外侧右边的内容,和输入框共用边框。放 HuiButton、HuiSelect 时边框自动合并 |
方法
| 名称 | 类型 | 说明 |
|---|---|---|
| focus | () => void | 让输入框获得焦点 |
| blur | () => void | 让输入框失去焦点 |
| select | () => void | 选中输入框里的全部文字 |
| clear | () => void | 可编辑时清空,依次触发 update:modelValue、input、clear、change;保留外部焦点 |
| inputRef | HTMLInputElement | 内部的 input 元素 |
工具函数
| 名称 | 类型 | 说明 |
|---|---|---|
| isMaskComplete | (value: string, mask: string, tokens?: Record<string, RegExp>) => boolean | 掩码的必填槽位是否填满,支持带格式或不带格式的值 |
类型
公开类型使用组件前缀。兼容映射:PasswordStrength → InputPasswordStrength。旧名仍可从 @nscode/handy-ui 导入,已标记 @deprecated,将在 1.0 删除。
import type {
InputProps,
InputEmits,
InputSize,
InputType,
InputPasswordStrength,
InputAllowPreset,
InputAllowInput
} from '@nscode/handy-ui'
import { getPasswordStrength, isMaskComplete } from '@nscode/handy-ui'
type InputSize = 'large' | 'default' | 'small'
type InputType = 'text' | 'password' | 'number' | 'email' | 'tel' | 'url'
type InputAllowPreset = 'digit' | 'int' | 'num' | 'alpha' | 'alnum' | 'hex'
type InputAllowInput = InputAllowPreset | RegExp | ((value: string) => boolean)
/** 密码强度:弱、中、强 */
type InputPasswordStrength = 'weak' | 'medium' | 'strong'
/** show-strength 的默认规则,也可以在自定义规则、表单校验里用 */
function getPasswordStrength(value: string): InputPasswordStrength
function isMaskComplete(value: string, mask: string, tokens?: Record<string, RegExp>): boolean
interface InputProps {
modelValue?: string | number | null
allowInput?: InputAllowInput
mask?: string
maskTokens?: Record<string, RegExp>
maskValue?: 'raw' | 'masked'
type?: InputType
size?: InputSize
placeholder?: string
disabled?: boolean
readonly?: boolean
clearable?: boolean
showPassword?: boolean
maxlength?: number
minlength?: number
showWordLimit?: boolean
prefixIcon?: string
suffixIcon?: string
autocomplete?: string
form?: string
validateEvent?: boolean
showStrength?: boolean
strengthMethod?: (value: string) => InputPasswordStrength
strengthTexts?: string[]
strengthLabel?: string
}
interface InputEmits {
'update:modelValue': [value: string | number]
input: [value: string | number]
change: [value: string | number]
focus: [event: FocusEvent]
blur: [event: FocusEvent]
clear: []
finish: [value: string]
}
焦点方法与公开类型
组件ref使用InputExpose。focus()聚焦当前、已选或首个可用控件,不改值、不打开文件选择框;禁用或卸载后不聚焦,只读按控件原合同保留可聚焦性。blur()只让本组件所属文档内的活动元素失焦,不影响外部焦点。组控件的focus/blur只在整组进出时各触发一次,内部移动不重复;既有表单校验行为保持。
clear()复用点击清空的原值与事件合同,禁用/只读时不执行,方法调用保留外部焦点;select()全选文本。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { InputExpose } from '@nscode/handy-ui'
const control = ref<InputExpose>()
const value = ref('文字')
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>
<HuiButton @mousedown.prevent @click="control?.select()">select()</HuiButton>
<HuiButton @mousedown.prevent @click="control?.clear()">clear()</HuiButton>
</HuiSpace>
<HuiInput
ref="control"
v-model="value"
clearable
@focus="event = 'focus'"
@blur="event = 'blur'"
/>
<span>{{ event }}</span>
</HuiSpace>
</template>
| 方法 | 签名 |
|---|---|
| focus | () => void |
| blur | () => void |