Input 输入框
单行文本输入框,用来输入用户名、搜索词、金额这类短文本。支持清空、密码显示切换、密码强度提示、字数统计、前后缀图标和插槽、前置和后置内容,放在 NsForm 里时会跟随表单的禁用、尺寸并触发校验。多行文本用 NsTextarea。
引入
import { NsInput } from '@ns/ui'
基础用法
用 v-model 绑定一个字符串,placeholder 是没有内容时显示的占位文字。
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput } from '@ns/ui'
const value = ref('')
</script>
<template>
<NsInput v-model="value" placeholder="请输入内容" />
<p style="margin-top: 12px">输入的内容:{{ value || '(空)' }}</p>
</template>
尺寸
size 可选 large、default、small,高度分别是 40、32、24px,字号 16、14、12px,圆角 8、6、4px,和同尺寸的 NsButton 一致。prefix-icon、suffix-icon 的图标和清空、显示密码按钮的图标比文字大 2px(18、16、14px),前后缀插槽里自己放的图标不受影响。放在 NsForm 里且没传 size 时,跟随表单项或表单的尺寸。
下面每一行是一种尺寸:带前缀图标的可清空输入框、带显示密码按钮的密码框,最后放一个同尺寸的按钮对比高度。
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsInput, NsSpace } from '@ns/ui'
const keyword = ref('输入框')
const password = ref('123456')
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<span class="row-label">large</span>
<NsInput v-model="keyword" size="large" prefix-icon="search" clearable style="width: 200px" />
<NsInput v-model="password" size="large" type="password" show-password style="width: 200px" />
<NsButton size="large">按钮</NsButton>
</NsSpace>
<NsSpace wrap>
<span class="row-label">default</span>
<NsInput v-model="keyword" prefix-icon="search" clearable style="width: 200px" />
<NsInput v-model="password" type="password" show-password style="width: 200px" />
<NsButton>按钮</NsButton>
</NsSpace>
<NsSpace wrap>
<span class="row-label">small</span>
<NsInput v-model="keyword" size="small" prefix-icon="search" clearable style="width: 200px" />
<NsInput v-model="password" size="small" type="password" show-password style="width: 200px" />
<NsButton size="small">按钮</NsButton>
</NsSpace>
</NsSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
禁用和只读
disabled 禁用后不能编辑,也不能聚焦;readonly 只读时可以聚焦、选中和复制文字,但不能修改。两种状态下都不显示清空按钮和密码切换按钮。在禁用的 NsForm 里也会被禁用。
下面第一行是禁用、第二行是只读,从左到右是有内容、没有内容(显示占位文字)、可清空的密码框:
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsSpace } from '@ns/ui'
const value = ref('不能修改的内容')
const empty = ref('')
const password = ref('123456')
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<span class="row-label">disabled</span>
<NsInput v-model="value" prefix-icon="user" disabled style="width: 200px" />
<NsInput v-model="empty" placeholder="禁用时的占位文字" disabled style="width: 200px" />
<NsInput
v-model="password"
type="password"
show-password
clearable
disabled
style="width: 200px"
/>
</NsSpace>
<NsSpace wrap>
<span class="row-label">readonly</span>
<NsInput v-model="value" prefix-icon="user" readonly style="width: 200px" />
<NsInput v-model="empty" placeholder="只读时的占位文字" readonly style="width: 200px" />
<NsInput
v-model="password"
type="password"
show-password
clearable
readonly
style="width: 200px"
/>
</NsSpace>
</NsSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 64px;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
可清空
clearable 为 true 且有内容时,右侧显示清空按钮。点它会把值清成 '',依次触发 update:modelValue、input、change、clear,然后让输入框重新获得焦点。清空按钮是一个带“清空”名称的 <button>,可以用 Tab 聚焦、回车触发。
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsMessage } from '@ns/ui'
const value = ref('点右侧按钮清空')
const onClear = () => {
NsMessage.info('已清空')
}
</script>
<template>
<NsInput v-model="value" clearable @clear="onClear" />
</template>
密码框
type="password" 时输入的内容显示成圆点。再加上 show-password,右侧会出现眼睛按钮,点击在明文和密文之间切换;不加时没有切换按钮,只能看到圆点。
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsSpace } from '@ns/ui'
const password = ref('123456')
const confirm = ref('')
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput v-model="password" type="password" placeholder="不带切换按钮" />
<NsInput v-model="confirm" type="password" show-password placeholder="带显示密码按钮" />
</NsSpace>
</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 { NsInput, NsSpace } from '@ns/ui'
const password = ref('')
const weak = ref('12345678')
const medium = ref('abcd1234')
const strong = ref('Abcd1234!')
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput
v-model="password"
type="password"
show-password
show-strength
placeholder="输入密码看强度"
/>
<NsInput v-model="weak" type="password" show-password show-strength />
<NsInput v-model="medium" type="password" show-password show-strength />
<NsInput v-model="strong" type="password" show-password show-strength />
</NsSpace>
</template>
自定义强度规则
strength-method 传一个函数自定义规则:参数是输入的密码(不会是空字符串),返回 'weak'、'medium'、'strong' 之一。返回其他值时不显示强度,开发环境下会在控制台警告。
只想在默认规则上加一点限制时,可以从 @ns/ui 导入 getPasswordStrength 接着用。下面第一个输入框是完全自定义的规则,第二个在默认规则的基础上把常见的弱密码一律算成弱:
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsSpace, getPasswordStrength } from '@ns/ui'
import type { PasswordStrength } from '@ns/ui'
const custom = ref('')
const extended = ref('Password123')
// 少于 10 位是弱;10 位及以上,同时有字母和数字是中,再加上符号是强
const customRule = (value: string): PasswordStrength => {
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): PasswordStrength =>
/password|123456|qwerty/i.test(value) ? 'weak' : getPasswordStrength(value)
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput
v-model="custom"
type="password"
show-password
show-strength
:strength-method="customRule"
placeholder="至少 10 位,字母、数字、符号都有才是强"
/>
<NsInput
v-model="extended"
type="password"
show-password
show-strength
:strength-method="extendedRule"
placeholder="带 password、123456 的算弱"
/>
</NsSpace>
</template>
强度文字
strength-texts 依次传弱、中、强三档的文字,英文界面这样改;没传的项用默认的“弱”“中”“强”。strength-label 是读屏软件在强度前面读出的说明,默认“密码强度”,界面上不显示,英文界面也一起改掉;传空字符串时只读强度文字。
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsSpace } from '@ns/ui'
const password = ref('abcd1234')
const texts = ['Too weak', 'Fair', 'Strong']
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput
v-model="password"
type="password"
show-password
show-strength
:strength-texts="texts"
strength-label="Password strength"
placeholder="Password"
/>
</NsSpace>
</template>
在表单里校验强度
强度提示只是提示,不会拦住提交。要求密码至少达到“中”时,在校验规则里用 getPasswordStrength(或者你自己的规则函数)判断。强度显示在输入框下面,校验不通过时错误提示排在强度下面:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { NsButton, NsForm, NsFormItem, NsInput, NsMessage, getPasswordStrength } from '@ns/ui'
import type { FormRule } from '@ns/ui'
const formRef = ref<InstanceType<typeof NsForm>>()
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) NsMessage.success('提交成功')
}
</script>
<template>
<NsForm ref="formRef" :model="model" :rules="rules" label-width="80px" @submit.prevent>
<NsFormItem label="新密码" prop="password">
<NsInput v-model="model.password" type="password" show-password show-strength />
</NsFormItem>
<NsFormItem>
<NsButton type="primary" @click="submit">提交</NsButton>
</NsFormItem>
</NsForm>
</template>
前后缀图标
prefix-icon、suffix-icon 传图标名,图标分别显示在输入框左侧和右侧,只用来装饰,不能点击。两个可以同时用。能用的图标名见 Icon 组件的文档。
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsSpace } from '@ns/ui'
const keyword = ref('')
const title = ref('')
const phone = ref('')
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput v-model="keyword" prefix-icon="search" placeholder="前缀图标(prefix-icon)" />
<NsInput v-model="title" suffix-icon="edit" placeholder="后缀图标(suffix-icon)" />
<NsInput v-model="phone" prefix-icon="phone" suffix-icon="lock" placeholder="前后都有" />
</NsSpace>
</template>
前缀、后缀插槽
需要放文字或自定义内容时用 prefix、suffix 插槽,插槽内容优先于 prefix-icon、suffix-icon。显示清空按钮或密码切换按钮时,后缀(插槽和图标)会让出位置,不显示:下面第三个输入框有内容时显示清空按钮,清空后才显示后缀“.com”。
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsIcon, NsSpace } from '@ns/ui'
const price = ref('')
const user = ref('')
const site = ref('example')
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput v-model="price" placeholder="金额">
<template #prefix>¥</template>
<template #suffix>元</template>
</NsInput>
<NsInput v-model="user" placeholder="用户名">
<template #prefix><NsIcon name="user" /></template>
</NsInput>
<NsInput v-model="site" clearable placeholder="域名">
<template #prefix>https://</template>
<template #suffix>.com</template>
</NsInput>
</NsSpace>
</template>
前置、后置内容
prepend、append 插槽的内容放在输入区外侧:和输入框共用一圈边框,中间用一条竖线隔开,带浅灰底色,只有两端是圆角。常用来放协议、域名后缀、单位这类固定文字。
和前缀、后缀的区别:prefix、suffix 在输入区里面,没有底色和竖线。两组可以同时用,也能和清空按钮、字数统计一起用;有内容时清空按钮只让后缀让位,后置内容一直显示。
<script setup lang="ts">
import { ref } from 'vue'
import { NsIcon, NsInput, NsSpace } from '@ns/ui'
const site = ref('example')
const receiver = ref('')
const subdomain = ref('docs')
const link = ref('')
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput v-model="site" clearable placeholder="域名">
<template #prepend>https://</template>
<template #append>.com</template>
</NsInput>
<NsInput v-model="receiver" prefix-icon="mail" placeholder="和前缀图标一起用">
<template #prepend>收件人</template>
</NsInput>
<NsInput v-model="subdomain" :maxlength="20" show-word-limit clearable>
<template #append>.example.com</template>
</NsInput>
<NsInput v-model="link" placeholder="前置里放图标">
<template #prepend><NsIcon name="link" /></template>
</NsInput>
</NsSpace>
</template>
前置、后置放按钮和选择器
插槽里直接放 NsButton、NsSelect 时,前置、后置区不再有底色和内边距,按钮、选择器自己的边框顶替输入框那一段的边框,接缝处只有一条线,外侧的圆角和输入框一致、里侧是直角。
- 选择器默认按内容宽,写
style="width: ..."固定宽度,切换选项时输入框才不会忽宽忽窄。 - 按钮、选择器的高度会撑满输入框,字号、内边距仍按它们自己的
size,输入框是large、small时给它们传同样的size。
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsInput, NsMessage, NsSelect, NsSpace } from '@ns/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 = () => {
NsMessage.info(keyword.value ? `搜索:${keyword.value}` : '请输入关键词')
}
const visit = () => {
NsMessage.info(`访问:${protocol.value}${host.value || 'example'}${suffix.value}`)
}
const step = (delta: number) => {
amount.value = String((Number(amount.value) || 0) + delta)
}
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput v-model="keyword" clearable placeholder="输入后按回车或点搜索" @keydown.enter="search">
<template #append>
<NsButton type="primary" icon="search" @click="search">搜索</NsButton>
</template>
</NsInput>
<NsInput v-model="host" placeholder="example">
<template #prepend>
<NsSelect v-model="protocol" :options="protocols" style="width: 100px" />
</template>
<template #append>
<NsSelect v-model="suffix" :options="suffixes" style="width: 90px" />
</template>
</NsInput>
<NsInput v-model="amount" placeholder="数量">
<template #prepend>
<NsButton icon="minus" aria-label="减 10" @click="step(-10)" />
</template>
<template #append>
<NsButton icon="plus" aria-label="加 10" @click="step(10)" />
</template>
</NsInput>
<NsInput v-model="host" placeholder="example">
<template #prepend>https://</template>
<template #append>
<NsButton @click="visit">访问</NsButton>
</template>
</NsInput>
</NsSpace>
</template>
前置、后置内容的尺寸和禁用
前置、后置内容跟着输入框的 size 变:文字的字号、左右内边距和输入框一样,三种尺寸都对齐。输入框禁用时,前置、后置的文字变成禁用色;里面放的按钮、选择器是独立的组件,要自己加 disabled。
<script setup lang="ts">
import { reactive } from 'vue'
import { NsButton, NsInput, NsSelect, NsSpace } from '@ns/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>
<NsSpace direction="vertical" align="start">
<NsSpace v-for="size in sizes" :key="size" wrap>
<span class="row-label">{{ size }}</span>
<NsInput v-model="hosts[size]" :size="size" style="width: 220px">
<template #prepend>https://</template>
<template #append>.com</template>
</NsInput>
<NsInput v-model="hosts[size]" :size="size" clearable style="width: 300px">
<template #prepend>
<NsSelect
v-model="protocols[size]"
:options="options"
:size="size"
style="width: 100px"
/>
</template>
<template #append>
<NsButton type="primary" :size="size">访问</NsButton>
</template>
</NsInput>
</NsSpace>
<NsSpace wrap>
<span class="row-label">disabled</span>
<NsInput model-value="example" disabled style="width: 220px">
<template #prepend>https://</template>
<template #append>.com</template>
</NsInput>
<NsInput model-value="example" disabled style="width: 300px">
<template #prepend>
<NsSelect model-value="https://" :options="options" disabled style="width: 100px" />
</template>
<template #append>
<NsButton type="primary" disabled>访问</NsButton>
</template>
</NsInput>
</NsSpace>
</NsSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 64px;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
前置、后置内容的校验状态
在出错的 NsFormItem 里,整圈边框(包括前置、后置区)变成危险色;里面放的选择器也一起变红,按钮保持自己的颜色。用开关切换表单项的 error 看看:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { NsButton, NsForm, NsFormItem, NsInput, NsSelect, NsSpace, NsSwitch } from '@ns/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>
<NsSpace direction="vertical" fill>
<NsSwitch v-model="showError" active-text="显示错误" />
<NsForm :model="model" label-width="80px" @submit.prevent>
<NsFormItem label="网址" :error="showError ? '网址里不能有空格' : ''">
<NsInput v-model="model.host" clearable>
<template #prepend>
<NsSelect v-model="model.protocol" :options="protocols" style="width: 100px" />
</template>
<template #append>.com</template>
</NsInput>
</NsFormItem>
<NsFormItem label="关键词" :error="showError ? '请输入关键词' : ''" size="large">
<NsInput v-model="model.keyword" prefix-icon="search">
<template #append>
<NsButton type="primary" size="large">搜索</NsButton>
</template>
</NsInput>
</NsFormItem>
<NsFormItem label="价格" :error="showError ? '价格不能小于 0' : ''" size="small">
<NsInput v-model="model.price">
<template #prepend>¥</template>
<template #append>元</template>
</NsInput>
</NsFormItem>
</NsForm>
</NsSpace>
</template>
字数统计
同时设置 maxlength 和 show-word-limit,右侧显示“已输入/上限”。只设 maxlength 时只限制长度,不显示统计;只设 show-word-limit 不起作用。字数统计和清空按钮可以同时显示,三种尺寸都能用。
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsSpace } from '@ns/ui'
const limitOnly = ref('')
const withCount = ref('')
const small = ref('小尺寸')
</script>
<template>
<NsSpace direction="vertical" fill>
<NsInput v-model="limitOnly" :maxlength="10" placeholder="最多 10 个字,不显示统计" />
<NsInput
v-model="withCount"
:maxlength="20"
show-word-limit
clearable
placeholder="最多 20 个字"
/>
<NsInput v-model="small" size="small" :maxlength="20" show-word-limit />
</NsSpace>
</template>
输入类型
type 可选 text、password、number、email、tel、url,对应原生 input 的类型,会影响手机上弹出的键盘。type="number" 时 v-model 拿到的仍然是字符串(如 "12"),需要数字时写 v-model.number;要限制范围、步长时用 NsInputNumber。
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { NsInput, NsSpace } from '@ns/ui'
const form = reactive({ text: '', password: '', email: '', tel: '', url: '' })
const age = ref<number | string>('')
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<span class="row-label">text</span>
<NsInput v-model="form.text" placeholder="普通文本(默认)" style="width: 240px" />
</NsSpace>
<NsSpace wrap>
<span class="row-label">password</span>
<NsInput v-model="form.password" type="password" placeholder="密码" style="width: 240px" />
</NsSpace>
<NsSpace wrap>
<span class="row-label">number</span>
<NsInput v-model.number="age" type="number" placeholder="年龄" style="width: 240px" />
<span>值:{{ age === '' ? '(空)' : age }},类型:{{ typeof age }}</span>
</NsSpace>
<NsSpace wrap>
<span class="row-label">email</span>
<NsInput v-model="form.email" type="email" placeholder="邮箱" style="width: 240px" />
</NsSpace>
<NsSpace wrap>
<span class="row-label">tel</span>
<NsInput v-model="form.tel" type="tel" placeholder="手机号" style="width: 240px" />
</NsSpace>
<NsSpace wrap>
<span class="row-label">url</span>
<NsInput v-model="form.url" type="url" placeholder="网址" style="width: 240px" />
</NsSpace>
</NsSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 64px;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
事件
输入时触发 input(和 update:modelValue 同时),内容有变化后失焦或按回车触发 change,获得、失去焦点触发 focus、blur,点清空按钮触发 clear。在下面的输入框里打字、按回车、点外面、点清空按钮,看看事件的顺序:
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput } from '@ns/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>
<NsInput
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>
校验状态
输入框没有单独的状态属性,出错的样子由所在的 NsFormItem 决定:校验不通过,或者给表单项传了 error 时,输入框的边框变成危险色,下面显示错误信息,内部的 <input> 带上 aria-invalid。下面用开关切换表单项的 error,三种尺寸都一样:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { NsForm, NsFormItem, NsInput, NsSwitch } from '@ns/ui'
const showError = ref(true)
const model = reactive({ username: 'admin', email: 'abc', phone: '123' })
</script>
<template>
<NsSwitch v-model="showError" active-text="显示错误" />
<NsForm :model="model" label-width="80px" style="margin-top: 16px" @submit.prevent>
<NsFormItem label="用户名" :error="showError ? '用户名已被占用' : ''" size="large">
<NsInput v-model="model.username" prefix-icon="user" clearable />
</NsFormItem>
<NsFormItem label="邮箱" :error="showError ? '邮箱格式不正确' : ''">
<NsInput v-model="model.email" prefix-icon="mail" />
</NsFormItem>
<NsFormItem label="手机号" :error="showError ? '请输入 11 位手机号' : ''" size="small">
<NsInput v-model="model.phone" :maxlength="11" show-word-limit />
</NsFormItem>
</NsForm>
</template>
原生属性和事件
组件上写的 class、style 留在最外层的容器上,其余属性和监听都透传到内部的 <input>:name、id、autofocus、tabindex、aria-label、data-*,以及 @keydown、@keyup、@paste 等组件没有声明的事件。autocomplete 是原生的自动填充属性,例如写 'off' 关掉浏览器的历史记录提示。
<script setup lang="ts">
import { ref } from 'vue'
import { NsInput, NsMessage } from '@ns/ui'
const keyword = ref('')
const search = () => {
NsMessage.info(`搜索:${keyword.value}`)
}
</script>
<template>
<NsInput
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 { NsInput, NsButton, NsSpace } from '@ns/ui'
const inputRef = ref<InstanceType<typeof NsInput>>()
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>
<NsInput ref="inputRef" v-model="value" @focus="focused = true" @blur="focused = false" />
<div style="margin-top: 12px">
<NsSpace wrap>
<NsButton @click="inputRef?.focus()">聚焦</NsButton>
<NsButton @click="inputRef?.blur()">失焦</NsButton>
<NsButton @click="inputRef?.select()">全选</NsButton>
<NsButton @click="inputRef?.clear()">清空</NsButton>
<NsButton @click="moveToEnd">光标移到末尾(inputRef)</NsButton>
</NsSpace>
</div>
<p style="margin-top: 12px">输入框{{ focused ? '已聚焦' : '没有聚焦' }}</p>
</template>
在表单里使用
放在 NsFormItem 里时,值变化触发 change 规则,失焦触发 blur 规则;表单项的 label 会通过 for 关联到输入框,校验出错时输入框带上 aria-invalid 和指向错误提示的 aria-describedby。不需要校验时设 :validate-event="false"。
<script setup lang="ts">
import { reactive } from 'vue'
import { NsForm, NsFormItem, NsInput } from '@ns/ui'
import type { FormRule } from '@ns/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>
<NsForm :model="model" :rules="rules" @submit.prevent>
<NsFormItem label="用户名" prop="username">
<NsInput v-model="model.username" />
</NsFormItem>
</NsForm>
</template>
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| modelValue | string | number | null | '' | 绑定值,支持 v-model。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 | - | 最小输入长度。原生属性,只在原生表单校验时起作用,不影响 NsForm |
| showWordLimit | boolean | false | 是否显示字数统计,需要同时设置 maxlength |
| prefixIcon | string | - | 前缀图标名 |
| suffixIcon | string | - | 后缀图标名 |
| autocomplete | string | - | 原生 autocomplete 属性,例如 'off'、'username' |
| form | string | - | 原生 form 属性:输入框所属 <form> 的 id |
| validateEvent | boolean | true | 值变化和失焦时是否触发所在表单项的校验 |
| showStrength | boolean | false | type 为 password 时,在输入框下方显示密码强度(强度条和文字)。没有输入内容时不显示 |
| strengthMethod | (value: string) => PasswordStrength | - | 自定义强度规则,参数是输入的密码(不为空),返回 '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() 后触发 |
Slots
| 插槽 | 作用域参数 | 说明 |
|---|---|---|
| prefix | - | 输入框左侧的内容,优先于 prefixIcon |
| suffix | - | 输入框右侧的内容,优先于 suffixIcon。显示清空、密码切换按钮时不显示 |
| prepend | - | 输入区外侧左边的内容,和输入框共用边框。放 NsButton、NsSelect 时边框自动合并 |
| append | - | 输入区外侧右边的内容,和输入框共用边框。放 NsButton、NsSelect 时边框自动合并 |
方法
| 名称 | 类型 | 说明 |
|---|---|---|
| focus | () => void | 让输入框获得焦点 |
| blur | () => void | 让输入框失去焦点 |
| select | () => void | 选中输入框里的全部文字 |
| clear | () => void | 清空。和点清空按钮一样触发 update:modelValue、input、change、clear 并聚焦 |
| inputRef | HTMLInputElement | 内部的 input 元素 |
类型
import type { InputProps, InputEmits, InputSize, InputType, PasswordStrength } from '@ns/ui'
import { getPasswordStrength } from '@ns/ui'
type InputSize = 'large' | 'default' | 'small'
type InputType = 'text' | 'password' | 'number' | 'email' | 'tel' | 'url'
/** 密码强度:弱、中、强 */
type PasswordStrength = 'weak' | 'medium' | 'strong'
/** show-strength 的默认规则,也可以在自定义规则、表单校验里用 */
function getPasswordStrength(value: string): PasswordStrength
interface InputProps {
modelValue?: string | number | null
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) => PasswordStrength
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: []
}
注意事项
- 用输入法打中文时,拼音组合期间不触发
update:modelValue和input,选字上屏后才触发一次,所以按拼音过滤列表时不会被中间的字母干扰。 - 输入框始终显示绑定值:父组件没有接收
update:modelValue,或者在回调里改写了值(比如去掉空格、转大写),输入框会马上显示成绑定值,不会和数据对不上。 type="number"时发出的值仍是字符串,需要数字时用v-model.number。- 只设
maxlength不设show-word-limit时不显示字数统计;show-word-limit单独设置不起作用。 - 显示清空按钮或密码切换按钮时,
suffix插槽和suffix-icon不显示。 clear()不检查禁用和只读状态,调用了就会清空。prepend、append里放的NsButton、NsSelect不跟随输入框的size、disabled,要自己传;选择器写style="width: ..."固定宽度。只有直接放在插槽里的按钮、选择器会合并边框,外面再包一层元素时按普通内容处理(有底色和内边距)。- 前置、后置只有单行的
NsInput有,多行文本NsTextarea没有。 - 密码强度只在
type="password"时显示,其他类型设了show-strength不起作用,开发环境下会在控制台警告。强度提示不拦截提交,需要时在表单校验规则里判断。 - 放在只有一个单行输入框的
NsForm里时,按回车会触发原生表单提交并刷新页面,给NsForm加@submit.prevent。
优化点
- [x] 支持
prepend、append复合输入框 - [ ] 支持输入格式化(
formatter、parser) - [ ] 支持输入历史记录