Input
A single-line input for short text such as usernames, search terms, and amounts. It supports clearing, password visibility and strength, character counts, prefix/suffix icons and slots, and prepend/append content. Within HuiForm, it follows form disabled state and size and triggers validation. Use HuiTextarea for multiline text.
Import
import { HuiInput } from '@nscode/handy-ui'
Internal and Controlled Values
Without modelValue, the input stores its value across unrelated parent renders. An update:modelValue listener alone also uses this mode. Prop presence makes it controlled, including explicit undefined and null, which display as empty. A parent that rejects updates keeps its original bound value displayed. There is no defaultValue prop. Adding or removing the binding at runtime warns in development and follows the new mode.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInput, HuiSpace } from '@nscode/handy-ui'
const redraw = ref(0)
const lastInput = ref('No input yet')
const record = (value: string | number) => {
lastInput.value = String(value)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="redraw++">Parent redraw:{{ redraw }}</HuiButton>
<HuiInput
:data-parent-render="redraw"
clearable
:maxlength="20"
show-word-limit
placeholder="Internal value, update listener only"
@update:model-value="record"
/>
<span>Latest update:{{ lastInput }}</span>
<HuiInput model-value="固定值" placeholder="Controlled: parent rejects updates" />
<HuiInput :model-value="undefined" placeholder="Explicit undefined: controlled empty value" />
<HuiInput :model-value="null" placeholder="Explicit null: controlled empty value" />
</HuiSpace>
</template>
Basic Usage
Bind a string with v-model. placeholder is shown when the input is empty.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput } from '@nscode/handy-ui'
const value = ref('')
</script>
<template>
<HuiInput v-model="value" placeholder="Enter text" />
<p style="margin-top: 12px">Input value:{{ value || '(empty)' }}</p>
</template>
Restricting Input
The six allow-input presets and regular expressions filter character by character, retaining only allowed characters when pasting. A function evaluates the entire proposed value; returning false restores the previous value and selection. An empty string is always allowed without calling the function, so the input can be cleared.
<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>Bound value:'{{ values[preset] }}'</p>
</div>
<div style="width: 180px">
<p>Regular expression: digits and decimal points</p>
<HuiInput
v-model="patternValue"
:allow-input="/[\d.]/"
placeholder="Character-by-character filter"
/>
<p>Bound value:'{{ patternValue }}'</p>
</div>
<div style="width: 180px">
<p>Function: up to two decimal places</p>
<HuiInput
v-model="decimalValue"
:allow-input="allowDecimal"
placeholder="Validate the whole value"
/>
<p>Bound value:'{{ decimalValue }}'</p>
</div>
</HuiSpace>
</template>
digit allows only 0-9. int additionally permits one leading minus sign. num also permits one decimal point, preserving intermediate -, ., and -. values. alpha permits English letters; alnum permits English letters and digits; hex permits 0-9, A-F, and a-f.
digit defaults to inputmode="numeric", while num uses inputmode="decimal". int leaves the keyboard type unspecified to allow a minus sign. Use digit for nonnegative integer entry with a numeric keyboard. An explicit inputmode takes precedence. Filtering covers typing, pasting, dropping, and committed IME input; externally supplied values are not filtered on assignment. The function for HuiInput receives the whole value, while HuiInputOtp receives one character.
When a decimal point already exists, another inserted or pasted point is filtered out, preserving the existing point and minus sign; selecting them allows replacement. Without a mask, combining allow-input with maxlength first filters the inserted segment and existing surrounding text, then calculates remaining capacity from the filtered surrounding text's UTF-16 length without splitting code points such as emoji. With a valid edit range, only the inserted segment is truncated; valid unedited surrounding text is preserved, and deletion does not truncate the existing value. Editing filters invalid characters from external values regardless of maxlength, while external assignment itself does not filter. Only whole-value updates without a valid snapshot, such as autofill, truncate the entire value. Function filters still check the whole candidate before limiting the insertion length.
<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>Insert a decimal point after 1: the original 12.5 remains unchanged</p>
<HuiInput v-model="amount" allow-input="num" />
<span>Amount:'{{ amount }}'</span>
<p>Paste a1b2c3: filter to 123, then apply the three-character limit</p>
<HuiInput v-model="code" allow-input="digit" :maxlength="3" show-word-limit />
<span>Code:'{{ code }}'</span>
<p>
Three characters are full: inserting 9 at the start keeps 123; select existing characters to
replace them
</p>
<HuiInput v-model="full" allow-input="digit" :maxlength="3" show-word-limit />
<span>Unedited content preserved:'{{ full }}'</span>
<p>
Four characters are full: pasting 99 after 1 keeps 1234; select 23 and paste a9b8c7 to obtain
1984
</p>
<HuiInput v-model="replacement" allow-input="digit" :maxlength="4" show-word-limit />
<span>Replacement result:'{{ replacement }}'</span>
</HuiSpace>
</template>
Input Masks
In mask, 9 represents a digit, a an English letter, and * an English letter or digit. A backslash escapes the next character, and content after ? is optional. Masks apply only to type="text" and type="tel". Intermediate separators appear when subsequent content exists, while closing literals appear once their segment is complete; for example (99) displays (12).
With the default mask-value="raw", the bound value excludes prefixes and separators. masked includes formatting. finish fires when the required portion becomes complete; adding optional content does not fire it again. External value updates do not emit finish.
A single code point from insertText or an IME commit is treated as raw input, avoiding accidental removal when it matches a literal. Multi-character insertion, dropping, whole-string IME commits, pasting, or replacement first strips the literal prefix and separators corresponding to the current slot. For example, inserting or dropping +8613800000000 displays +86 138 0000 0000 with raw value 13800000000; prefix digits are excluded from the number and the finish argument.
<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(`Completed: ${value}`)
</script>
<template>
<HuiSpace wrap align="start">
<div style="width: 220px">
<p>Phone number (raw)</p>
<HuiInput
v-model="phone"
mask="999 9999 9999"
placeholder="138 0000 0000"
@finish="finished"
/>
<p>Bound value:'{{ phone }}'</p>
</div>
<div style="width: 220px">
<p>Bank card (16 required digits, 3 optional digits)</p>
<HuiInput
v-model="card"
mask="9999 9999 9999 9999? 999"
placeholder="16 or 19 digits"
@finish="finished"
/>
<p>Bound value:'{{ card }}'</p>
</div>
<div style="width: 220px">
<p>Literal prefix: paste, drop, or insert +8613800000000 as a whole string</p>
<HuiInput
v-model="prefixed"
mask="+86 999 9999 9999"
allow-input="digit"
type="tel"
placeholder="+86 138 0000 0000"
@finish="finished"
/>
<p>Bound value:'{{ prefixed }}'</p>
</div>
<div style="width: 220px">
<p>Phone number (masked)</p>
<HuiInput
v-model="formatted"
mask="999 9999 9999"
mask-value="masked"
placeholder="Including separators"
@finish="finished"
/>
<p>Bound value:'{{ formatted }}'</p>
</div>
<div style="width: 220px">
<p>Closing literal (masked)</p>
<HuiInput v-model="closed" mask="(99)" mask-value="masked" @finish="finished" />
<p>Parentheses are included after both digits are filled:'{{ closed }}'</p>
</div>
</HuiSpace>
</template>
Custom Mask Tokens
mask-tokens extends or overrides tokens. Below, X restricts the characters in a business registration code. Regular expressions with g or y flags still work across consecutive input without losing characters.
<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-character business registration code"
/>
<span>Bound value:'{{ value }}'</span>
<HuiInput
v-model="escaped"
:mask="escapedMask"
placeholder="Literal 9 + two letters + two digits"
/>
<span>Escaped prefix 9 is excluded from the raw value:'{{ escaped }}'</span>
</HuiSpace>
</template>
Mask Validation in Forms
Blurring an incomplete mask preserves its content; the form decides whether submission is allowed. isMaskComplete accepts raw or masked values and custom tokens. Prefixes and separators are matched from the beginning of literal segments without requiring full formatting: '+861' and '+86 1' are both incomplete for '+86 999'. Pasting or autofilling +8613800000000, +86-138-0000-0000, or 13800000000 yields the same number. Numeric literals can overlap raw input: '99' for '\\999' is treated as literal 9 plus one valid digit. Pass the complete displayed value, such as '999', to resolve this ambiguity.
<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: 'Complete the 11-digit phone number',
trigger: 'blur'
}
]
}
const submit = async () => {
if ((await formRef.value!.validate()).valid) HuiMessage.success(`Phone number: ${model.phone}`)
}
</script>
<template>
<HuiForm ref="formRef" :model="model" :rules="rules" label-width="80px" @submit.prevent>
<HuiFormItem label="Phone number" prop="phone">
<HuiInput v-model="model.phone" :mask="mask" placeholder="138 0000 0000" />
</HuiFormItem>
<HuiFormItem
><HuiButton type="primary" @click="submit">Validate and submit</HuiButton></HuiFormItem
>
</HuiForm>
</template>
Sizes
size accepts large, default, or small, with heights of 40/32/24px, font sizes of 16/14/12px, and corner radii of 8/6/4px, matching HuiButton. Prefix/suffix icons and clear/password-toggle icons are 2px larger than the text (18/16/14px); custom slot icons are unaffected. Within HuiForm, omitted size follows the form item or form.
Each row below compares a clearable input with a prefix icon, a password input with a visibility toggle, and a button at the same 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">Button</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>Button</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">Button</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 and Read-Only States
A disabled input cannot be edited or focused. A read-only input can receive focus and supports selection and copying, but cannot be edited. Both states hide the clear and password-toggle buttons. A disabled HuiForm also disables the input.
The first row is disabled and the second read-only. Each shows an input with content, an empty input with a placeholder, and a clearable password input.
<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 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="Read-only 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>
Clearing
When clearable=true and content is present, a clear button appears on the right. Clicking requests '' and emits update:modelValue, input, clear, and change in that order, then restores input focus. The native <button> has a localized Clear name and supports Tab focus and Enter activation.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiMessage } from '@nscode/handy-ui'
const value = ref('点右侧按钮清空')
const onClear = () => {
HuiMessage.info('Cleared')
}
</script>
<template>
<HuiInput v-model="value" clearable @clear="onClear" />
</template>
Password Inputs
type="password" masks the input with dots. Add show-password for an eye button on the right that toggles between visible and masked text. Without it, there is no toggle.
<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="Without a visibility toggle" />
<HuiInput
v-model="confirm"
type="password"
show-password
placeholder="With a visibility toggle"
/>
</HuiSpace>
</template>
Password Strength
For type="password", show-strength displays a three-segment strength bar and text below the input: weak lights one danger-colored segment, medium two warning-colored segments, and strong three success-colored segments. Empty values show no strength indicator. Space is reserved below the input when visible, moving form errors down accordingly.
The default getPasswordStrength rule treats fewer than 8 characters as weak. At 8 or more, lowercase letters, uppercase letters, digits, and symbols each contribute 1 point, with 1 extra point at 12 characters. A score of 1 is weak, 2 medium, and 3 or more strong.
Strength changes are announced by screen readers, such as Password strength: Medium. The input also references the indicator through aria-describedby, so it is announced on focus.
Try the first input below. The remaining inputs demonstrate weak, medium, and strong passwords; use the eye buttons to inspect them.
<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="Enter a password to see its strength"
/>
<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>
Custom Strength Rules
Pass a function to strength-method. It receives the nonempty password and returns 'weak', 'medium', or 'strong'. Other results hide the indicator and warn in development.
Import getPasswordStrength from @nscode/handy-ui to extend the default rule. The first input below uses a fully custom rule; the second adds a common-weak-password check to the default rule.
<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')
// Below 10 characters is weak; at least 10 with letters and digits is medium, plus symbols is strong
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'
}
// Default rule, additionally treating password, 123456, or qwerty as weak
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="At least 10 characters; letters, digits, and symbols for strong"
/>
<HuiInput
v-model="extended"
type="password"
show-password
show-strength
:strength-method="extendedRule"
placeholder="Containing password or 123456 is weak"
/>
</HuiSpace>
</template>
Strength Labels
strength-texts provides weak, medium, and strong labels in that order; omitted entries use the locale. strength-label is the screen-reader prefix before the strength and defaults to the localized Password strength. It is not visually displayed; an empty string announces only the strength text. Use these props for local customization, or see Internationalization to change the whole application's locale.
<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>
Validating Password Strength
The strength indicator does not block submission. To require at least medium strength, use getPasswordStrength or your own function in a validation rule. The indicator appears below the input, with validation errors below it.
<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: 'Enter a password', trigger: 'blur' },
{
validator: (_rule, value) => getPasswordStrength(String(value ?? '')) !== 'weak',
message:
'Password too weak: at least 8 characters and two or more of letters, digits, and symbols',
trigger: 'blur'
}
]
}
const submit = async () => {
const { valid } = await formRef.value!.validate()
if (valid) HuiMessage.success('Submitted successfully')
}
</script>
<template>
<HuiForm ref="formRef" :model="model" :rules="rules" label-width="80px" @submit.prevent>
<HuiFormItem label="New password" prop="password">
<HuiInput v-model="model.password" type="password" show-password show-strength />
</HuiFormItem>
<HuiFormItem>
<HuiButton type="primary" @click="submit">Submit</HuiButton>
</HuiFormItem>
</HuiForm>
</template>
Prefix and Suffix Icons
Pass icon names to prefix-icon and suffix-icon for decorative, non-clickable icons on the left and right. Both can be used together. See the Icon documentation for available names.
<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 (prefix-icon)" />
<HuiInput v-model="title" suffix-icon="edit" placeholder="Suffix icon (suffix-icon)" />
<HuiInput
v-model="phone"
prefix-icon="phone"
suffix-icon="lock"
placeholder="Icons on both sides"
/>
</HuiSpace>
</template>
Prefix and Suffix Slots
Use prefix and suffix for text or custom content. Slots take precedence over the icon props. A visible clear or password-toggle button hides the suffix slot and icon. The third input below shows its clear button while populated and the .com suffix after clearing.
<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="Amount">
<template #prefix>¥</template>
<template #suffix>CNY</template>
</HuiInput>
<HuiInput v-model="user" placeholder="Username">
<template #prefix><HuiIcon name="user" /></template>
</HuiInput>
<HuiInput v-model="site" clearable placeholder="Domain">
<template #prefix>https://</template>
<template #suffix>.com</template>
</HuiInput>
</HuiSpace>
</template>
Prepend and Append Content
prepend and append sit outside the text area, sharing its outer border with a vertical separator and pale gray background. Only the outer ends are rounded. They suit fixed content such as protocols, domain suffixes, or units.
In contrast, prefix and suffix are inside the text area without a separate background or border. Both pairs work together and with clearing or character counts. The clear button replaces only the suffix, while append content remains visible.
<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="Domain">
<template #prepend>https://</template>
<template #append>.com</template>
</HuiInput>
<HuiInput v-model="receiver" prefix-icon="mail" placeholder="With a prefix icon">
<template #prepend>Recipient</template>
</HuiInput>
<HuiInput v-model="subdomain" :maxlength="20" show-word-limit clearable>
<template #append>.example.com</template>
</HuiInput>
<HuiInput v-model="link" placeholder="Icon in prepend">
<template #prepend><HuiIcon name="link" /></template>
</HuiInput>
</HuiSpace>
</template>
Buttons and Selects in Prepend or Append
When HuiButton or HuiSelect is placed directly in these slots, the addon loses its background and padding. The nested control's border replaces that portion of the input border, with one line at the join, matching outer corners, and square inner corners.
- Selects use content width by default. Set
style="width: ..."to avoid width changes when selecting options. - Buttons and selects fill the input height, but retain font size and padding from their own
size. Match their size to a large or small input.
<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 ? `Search: ${keyword.value}` : 'Enter keywords')
}
const visit = () => {
HuiMessage.info(`Visit: ${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="Press Enter or click Search"
@keydown.enter="search"
>
<template #append>
<HuiButton type="primary" icon="search" @click="search">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="Quantity">
<template #prepend>
<HuiButton icon="minus" aria-label="Subtract 10" @click="step(-10)" />
</template>
<template #append>
<HuiButton icon="plus" aria-label="Add 10" @click="step(10)" />
</template>
</HuiInput>
<HuiInput v-model="host" placeholder="example">
<template #prepend>https://</template>
<template #append>
<HuiButton @click="visit">Visit</HuiButton>
</template>
</HuiInput>
</HuiSpace>
</template>
Addon Sizes and Disabled State
Addon font size and horizontal padding follow the input size, aligning in all three sizes. A disabled input changes addon text to the disabled color. Nested buttons and selects are independent components and require their own disabled prop.
<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">Visit</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>Visit</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>
Addon Validation State
Within an invalid HuiFormItem, the full border, including addons, uses the danger color. A nested select also turns red, while buttons retain their own colors. Toggle the form item's error below.
<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="Show errors" />
<HuiForm :model="model" label-width="80px" @submit.prevent>
<HuiFormItem label="URL" :error="showError ? 'The URL cannot contain spaces' : ''">
<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="Keywords" :error="showError ? 'Enter keywords' : ''" size="large">
<HuiInput v-model="model.keyword" prefix-icon="search">
<template #append>
<HuiButton type="primary" size="large">Search</HuiButton>
</template>
</HuiInput>
</HuiFormItem>
<HuiFormItem
label="Price"
:error="showError ? 'The price cannot be below 0' : ''"
size="small"
>
<HuiInput v-model="model.price">
<template #prepend>¥</template>
<template #append>CNY</template>
</HuiInput>
</HuiFormItem>
</HuiForm>
</HuiSpace>
</template>
Character Counts
Set both maxlength and show-word-limit to display the current length and limit on the right. maxlength alone only limits input, and show-word-limit alone has no effect. The counter works alongside the clear button in all three sizes.
<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="At most 10 characters, without a counter"
/>
<HuiInput
v-model="withCount"
:maxlength="20"
show-word-limit
clearable
placeholder="At most 20 characters"
/>
<HuiInput v-model="small" size="small" :maxlength="20" show-word-limit />
</HuiSpace>
</template>
Input Types
type accepts native input types text, password, number, email, tel, and url, affecting mobile keyboards. type="number" still produces a string such as "12"; use v-model.number for numeric conversion. Use HuiInputNumber for bounds and stepping.
<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="Plain text (default)" style="width: 240px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">password</span>
<HuiInput
v-model="form.password"
type="password"
placeholder="Password"
style="width: 240px"
/>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">number</span>
<HuiInput v-model.number="age" type="number" placeholder="Age" style="width: 240px" />
<span>Value:{{ age === '' ? '(empty)' : age }}, type:{{ typeof age }}</span>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">email</span>
<HuiInput v-model="form.email" type="email" placeholder="Email" style="width: 240px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">tel</span>
<HuiInput v-model="form.tel" type="tel" placeholder="Phone number" style="width: 240px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">url</span>
<HuiInput v-model="form.url" type="url" placeholder="URL" 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>
Interaction Events
Input emits input together with update:modelValue. Changed content emits change on blur or Enter; focus transitions emit focus and blur, and the clear button emits clear. Type, press Enter, click outside, or clear below to inspect their order.
<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="Try entering some text"
@input="onInput"
@change="onChange"
@focus="log('focus')"
@blur="log('blur')"
@clear="log('clear')"
/>
<p style="margin-top: 12px">Latest events (newest first):{{ logs.join(',') || 'None yet' }}</p>
</template>
Validation State
The input has no separate status prop. Its HuiFormItem determines error appearance: failed validation or an explicit error gives the border a danger color, displays an error below, and adds aria-invalid to the native input. Toggle errors below in all three sizes.
<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="Show errors" />
<HuiForm :model="model" label-width="80px" style="margin-top: 16px" @submit.prevent>
<HuiFormItem
label="Username"
:error="showError ? 'Username is already taken' : ''"
size="large"
>
<HuiInput v-model="model.username" prefix-icon="user" clearable />
</HuiFormItem>
<HuiFormItem label="Email" :error="showError ? 'Invalid email format' : ''">
<HuiInput v-model="model.email" prefix-icon="mail" />
</HuiFormItem>
<HuiFormItem
label="Phone number"
:error="showError ? 'Enter an 11-digit phone number' : ''"
size="small"
>
<HuiInput v-model="model.phone" :maxlength="11" show-word-limit />
</HuiFormItem>
</HuiForm>
</template>
Native Attributes and Events
class and style remain on the outer container. Reserved border-state markers data-hui-field, data-invalid, data-disabled, data-open, and data-filled belong on the bordered root, consistently in client rendering and SSR. Other attributes and listeners pass through to the native input: name, id, autofocus, tabindex, aria-label, other data attributes, and undeclared events such as keydown, keyup, and paste. autocomplete is native, with 'off' disabling browser history suggestions.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiMessage } from '@nscode/handy-ui'
const keyword = ref('')
const search = () => {
HuiMessage.info(`Search: ${keyword.value}`)
}
</script>
<template>
<HuiInput
v-model="keyword"
name="keyword"
autocomplete="off"
aria-label="Search keywords"
placeholder="Press Enter to search"
class="search-box"
@keydown.enter="search"
/>
</template>
Calling Methods
Use the ref to call focus(), blur(), select(), or clear(), or access the native input through inputRef.
<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()">Focus</HuiButton>
<HuiButton @click="inputRef?.blur()">Blur</HuiButton>
<HuiButton @click="inputRef?.select()">Select all</HuiButton>
<HuiButton @click="inputRef?.clear()">Clear</HuiButton>
<HuiButton @click="moveToEnd">Move the caret to the end (inputRef)</HuiButton>
</HuiSpace>
</div>
<p style="margin-top: 12px">Input: {{ focused ? 'Focused' : 'Not focused' }}</p>
</template>
Form Integration
Within HuiFormItem, value changes trigger change rules and blur triggers blur rules. The item's label uses for to reference the input. Errors add aria-invalid and aria-describedby pointing to the error message. Set :validate-event="false" to disable validation triggers.
<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: 'Enter a username', trigger: 'blur' },
{ min: 3, max: 12, message: 'Length must be 3 to 12 characters', trigger: 'change' }
]
}
</script>
<template>
<HuiForm :model="model" :rules="rules" @submit.prevent>
<HuiFormItem label="Username" prop="username">
<HuiInput v-model="model.username" />
</HuiFormItem>
</HuiForm>
</template>
Ancestor Variable Overrides
--hui-input-padding-x controls horizontal input padding, retaining size defaults of 16px for large, 12px for default, and 8px for small. Set it on the input or any ancestor. Below, the outer element uses 20px and a nested element uses 8px, while each input keeps its own height, font size, and corner radius.
Prepend and append content use the same padding. On a side with an addon, the addon supplies spacing while that side of the input wrapper remains at 0; compensation between text and separator updates accordingly. Addon buttons and selects retain their edge-aligned layout. Override the variable without selecting internal nodes; an ancestor class in the parent's scoped style works without :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>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>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">Current input:{{ values.normal }}</span>
</div>
</template>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| modelValue | string | number | null | undefined | Prop presence enables controlled mode; omission maintains internal state from an empty string. Explicit null/undefined display empty |
| type | 'text' | 'password' | 'number' | 'email' | 'tel' | 'url' | 'text' | Native input type |
| size | 'large' | 'default' | 'small' | - | Size; follows the form when omitted, otherwise defaults to 'default' outside forms |
| placeholder | string | - | Placeholder |
| disabled | boolean | false | Whether disabled |
| readonly | boolean | false | Whether read-only |
| clearable | boolean | false | Whether to show a clear button when content is present |
| showPassword | boolean | false | Whether password inputs show a visibility toggle |
| maxlength | number | - | Maximum input length |
| minlength | number | - | Native minimum length, affecting native form validation only, not HuiForm |
| showWordLimit | boolean | false | Whether to show a character counter; also requires maxlength |
| prefixIcon | string | - | Prefix icon name |
| suffixIcon | string | - | Suffix icon name |
| autocomplete | string | - | Native autocomplete, such as 'off' or 'username' |
| form | string | - | Native form attribute: id of the form owning the input |
| allowInput | InputAllowInput | - | Preset or regexp character filtering, or a whole-value function that rejects input with false. Empty strings are always allowed |
| mask | string | - | Mask: 9 digit, a letter, * letter/digit, backslash escape, optional content after ?. Applies only to text and tel |
| maskTokens | Record<string, RegExp> | - | Extend or override mask tokens |
| maskValue | 'raw' | 'masked' | 'raw' | Whether the bound value excludes formatting or includes prefixes and separators |
| validateEvent | boolean | true | Whether value changes and blur trigger form-item validation |
| showStrength | boolean | false | Show a strength bar and text below password inputs; hidden for empty values |
| strengthMethod | (value: string) => InputPasswordStrength | - | Custom rule receiving a nonempty password and returning weak, medium, or strong. Defaults to getPasswordStrength |
| strengthTexts | string[] | Localized (Chinese: ['弱', '中', '强']) | Weak, medium, and strong labels in that order; omitted entries use the locale |
| strengthLabel | string | Localized (English: Password strength) | Screen-reader prefix before strength text, not visually displayed; empty string omits the prefix |
Events
| Event | Callback arguments | Description |
|---|---|---|
| update:modelValue | (value: string | number) | Emitted with the input string on input; suppressed during IME composition and emitted once on commit |
| input | (value: string | number) | Emitted together with update:modelValue |
| change | (value: string | number) | Native change after edited content blurs or Enter is pressed; also emitted with '' on clearing |
| focus | (event: FocusEvent) | Emitted on focus |
| blur | (event: FocusEvent) | Emitted on blur |
| clear | - | Emitted after the clear button or clear() is invoked |
| finish | (value: string) | Emitted when required mask slots become complete; the argument follows maskValue. Not emitted for external assignment |
Slots
| Slot | Scope arguments | Description |
|---|---|---|
| prefix | - | Content inside the left edge, overriding prefixIcon |
| suffix | - | Content inside the right edge, overriding suffixIcon; hidden while a clear or password-toggle button is displayed |
| prepend | - | Left addon sharing the input border; HuiButton and HuiSelect borders merge automatically |
| append | - | Right addon sharing the input border; HuiButton and HuiSelect borders merge automatically |
Methods
| Name | Type | Description |
|---|---|---|
| focus | () => void | Focus the input |
| blur | () => void | Blur the input |
| select | () => void | Select all input text |
| clear | () => void | Clear when editable, emitting update:modelValue, input, clear, then change; preserves external focus |
| inputRef | HTMLInputElement | Native input element |
Utilities
| Name | Type | Description |
|---|---|---|
| isMaskComplete | (value: string, mask: string, tokens?: Record<string, RegExp>) => boolean | Whether required mask slots are complete; accepts formatted or raw values |
Types
Public types use the component prefix. The compatibility mapping is PasswordStrength → InputPasswordStrength. The old name remains importable from @nscode/handy-ui, is deprecated, and will be removed in 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)
/** Password strength: weak, medium, strong */
type InputPasswordStrength = 'weak' | 'medium' | 'strong'
/** Default show-strength rule, also usable in custom rules and form validation */
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]
}
Focus Methods and Public Types
Use InputExpose for the component ref. focus() focuses the current, selected, or first available control without changing its value or opening a file chooser. Disabled or unmounted controls are not focused; read-only controls retain their existing focusability. blur() affects only this component's active element in its own document, preserving external focus. Group controls emit focus/blur once on entering or leaving the group, not on internal movement. Existing form-validation behavior is preserved.
clear() reuses the clear button's value and event behavior, does nothing when disabled or read-only, and preserves external focus. select() selects all text.
<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('Waiting for an action')
</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>
| Method | Signature |
|---|---|
| focus | () => void |
| blur | () => void |