尧图精选

Vant 4 PasswordInput 密码输入框组件实战指南:与数字键盘联动、API 详解与源码级实现原理

🕒 发布时间:2026/9/12 10:22:28 📁 来源:尧图网络
Vant 4 PasswordInput 密码输入框组件实战指南与数字键盘联动、API 详解与源码级实现原理【免费下载链接】vantA lightweight, customizable Vue UI library for mobile web apps.项目地址: https://gitcode.com/GitHub_Trending/va/vant导读PasswordInput密码输入框是 Vant 移动端组件库中专用于密码、短信验证码等敏感信息输入的网格型输入框组件。它不包含真正的键盘而是通过与 NumberKeyboard 数字键盘 组件配对使用在移动端 H5 场景下替代原生输入法从而获得对输入内容、长度与展示形式的完全控制。阅读本文后你将掌握 PasswordInput 的安装注册、五种典型使用场景基础用法、自定义长度、格子间距、明文展示、提示信息/错误提示、完整的 Props 与 Events API、基于 CSS 变量的主题定制方法并能通过源码解析理解其渲染与交互的底层原理。一、组件定位为什么需要 PasswordInput在移动端 Web 开发中支付密码、短信验证码等输入场景存在两个痛点输入法不可控原生键盘无法限制只能输入数字也无法拦截复制粘贴行为视觉不统一iOS / Android 上原生输入框样式差异大难以与业务 UI 保持一致。Vant 的 PasswordInput 组件给出的解决方案是纯展示 外部驱动的架构它本身不监听键盘输入而是通过value属性接收外部传入的密码字符串通过focused属性控制光标展示并将用户点击行为通过focus事件抛给外部——通常由 NumberKeyboard 数字键盘接收并回写value。这种展示层与输入层解耦的设计让密码输入场景的每一环都可控、可定制。从源码结构看该组件是一个典型的无状态stateless展示组件其实现位于 PasswordInput.tsx样式位于 index.less并配有独立测试test/index.spec.ts与在线 demodemo/index.vue。二、安装与注册PasswordInput 与 NumberKeyboard 均为 Vant 顶层导出组件。按需引入后通过app.use全局注册import { createApp } from vue; import { PasswordInput, NumberKeyboard } from vant; const app createApp(); app.use(PasswordInput); app.use(NumberKeyboard);注册后即可在模板中使用van-password-input与van-number-keyboard标签。更多注册方式如全量引入、按需自动引入、局部注册可参考 Vant 的 组件注册指南 与 快速上手文档。组件还通过 index.ts 声明了VanPasswordInput全局组件类型便于 TypeScript 项目在模板中获得类型提示。三、基础用法与数字键盘联动PasswordInput 最核心的使用模式是与 NumberKeyboard 组合成一个完整的密码输入闭环van-password-input :valuevalue :focusedshowKeyboard focusshowKeyboard true / van-number-keyboard v-modelvalue :showshowKeyboard blurshowKeyboard false /import { ref } from vue; export default { setup() { const value ref(123); const showKeyboard ref(true); return { value, showKeyboard, }; }, };整个交互链路可以拆解为四个步骤点击输入框用户触碰 PasswordInput 的网格区域组件抛出focus事件业务侧将showKeyboard置为true弹出键盘show属性为true时NumberKeyboard 自底部弹出输入回写键盘的input/delete事件更新valuePasswordInput 通过value属性感知变化并重新渲染网格点收起键盘键盘失焦blur时业务侧将showKeyboard置为falsefocused随之变为false光标消失。值得一提的是PasswordInput 的源码PasswordInput.tsx在touchstart阶段就触发focus事件比click更快响应能显著减少移动端键盘弹出的延迟感const onTouchStart (event: TouchEvent) { event.stopPropagation(); emit(focus, event); };同时通过event.stopPropagation()阻止事件冒泡避免与页面上其他点击行为如van-cell的点击相互干扰。四、五种使用场景详解4.1 自定义长度通过length属性设置密码位数例如 4 位短信验证码场景van-password-input :valuevalue :length4 :focusedshowKeyboard focusshowKeyboard true /length的类型为_number | string_源码中使用makeNumericProp(6)声明见 PasswordInput.tsx即传入数字或数字字符串均可组件内部会通过props.length将其转换为数字后用于渲染循环见renderPoints中const length props.length。4.2 格子间距gutter用于设置格子之间的间距产生分隔卡片式的视觉效果van-password-input :valuevalue :gutter10 :focusedshowKeyboard focusshowKeyboard true /gutter同样为_number | string_类型默认值为0。传入数值时默认单位为px也支持20px、2em等带单位的字符串。源码通过工具函数addUnit统一处理单位实现见 utils/format.tsexport function addUnit(value?: Numeric): string | undefined { if (isDef(value)) { return isNumeric(value) ? ${value}px : String(value); } return undefined; }gutter的存在与否还直接影响两个渲染细节源码 PasswordInput.tsx有gutter时每个格子通过marginLeft产生间距且格子之间不再绘制分隔线无gutter时格子间绘制BORDER_LEFT分隔线整个网格使用BORDER_SURROUND圆角边框包裹。4.3 明文展示将mask设为false可明文展示输入内容适用于短信验证码等无需遮挡的场景van-password-input :valuevalue :maskfalse :focusedshowKeyboard focusshowKeyboard true /从源码实现看mask使用truthProp声明PasswordInput.tsx默认值为true。渲染每个格子时若mask为真则输出一个隐藏/显示控制的圆点i元素否则直接输出字符本身PasswordInput.tsx{mask ? ( i style{{ visibility: char ? visible : hidden }} / ) : ( char )}注意一个细节mask 模式下圆点通过visibility而非条件渲染控制显隐这保证了每个格子的圆点始终占位网格布局不会因字符增减而抖动。4.4 提示信息与错误提示info属性用于在输入框下方展示普通提示文字error-info用于展示错误提示且优先级高于info——当两者同时存在时只渲染error-info源码 PasswordInput.tsx 中const info props.errorInfo || props.info;van-password-input :valuevalue infoSome tips :error-infoerrorInfo :focusedshowKeyboard focusshowKeyboard true / van-number-keyboard v-modelvalue :showshowKeyboard blurshowKeyboard false /import { ref, watch } from vue; export default { setup() { const value ref(123); const errorInfo ref(); const showKeyboard ref(true); watch(value, (newVal) { if (newVal.length 6 newVal ! 123456) { errorInfo.value Password Mistake; } else { errorInfo.value ; } }); return { value, errorInfo, showKeyboard, }; }, };上面的示例展示了输入 6 位且密码错误时展示红色错误提示的典型校验逻辑通过watch监听value变化动态写入或清空errorInfo。渲染时若当前显示的是错误信息则使用van-password-input__error-info类默认红色否则使用van-password-input__info类次要文字色两者的颜色分别由--van-password-input-error-info-color与--van-password-input-info-color控制。五、API 参考Props参数说明类型默认值value密码值stringinfo输入框下方文字提示string-error-info输入框下方错误提示string-length密码最大长度number | string6gutter输入框格子之间的间距如20px2em默认单位为pxnumber | string0mask是否隐藏密码内容booleantruefocused是否已聚焦聚焦时会显示光标booleanfalseEvents事件名说明回调参数focus输入框聚焦时触发在touchstart阶段触发见 PasswordInput.tsx-类型定义组件导出以下 TypeScript 类型便于在业务代码中进行受控 props 的类型约束import type { PasswordInputProps } from vant;PasswordInputProps由ExtractPropTypes从组件 props 定义自动推导见 PasswordInput.tsx同时组件在 types.ts 中额外导出了PasswordInputThemeVars主题变量类型。六、源码实现网格渲染与光标原理PasswordInput 的核心渲染逻辑集中在renderPoints函数PasswordInput.tsx逐格渲染的关键规则如下长度控制const length props.length将length转数字后循环生成对应数量的li格子字符填充取value[i]作为第 i 个格子的内容mask为真时渲染圆点否则渲染字符分隔线i ! 0 !gutter时给格子追加BORDER_LEFT左侧分隔线无gutter时整个网格用BORDER_SURROUND包裹圆角边框PasswordInput.tsx光标展示focused i value.length时在当前输入位置即最后一个字符的下一个格子渲染闪烁光标div classvan-password-input__cursor /聚焦状态类光标所在格子会附加van-password-input__item--focus类用于高亮当前输入位。光标的闪烁效果由样式文件 index.less 中的van-cursor-flicker关键帧动画驱动.van-password-input__cursor { position: absolute; top: 50%; left: 50%; width: var(--van-password-input-cursor-width); height: var(--van-password-input-cursor-height); background: var(--van-password-input-cursor-color); transform: translate(-50%, -50%); animation: var(--van-password-input-cursor-duration) van-cursor-flicker infinite; } keyframes van-cursor-flicker { from { opacity: 0; } 50% { opacity: 1; } 100% { opacity: 0; } }动画周期由--van-password-input-cursor-duration默认1s控制。整套渲染逻辑可以通过单元测试验证测试用例test/index.spec.ts覆盖了点击网格触发focus事件与error-info正确渲染两个核心行为test(should emit focus event when security is touched, () { const wrapper mount(PasswordInput); wrapper.find(.van-password-input__security).trigger(touchstart); expect(wrapper.emitted(focus)).toHaveLength(1); }); test(should render error info correctly, () { const wrapper mount(PasswordInput, { props: { errorInfo: error! }, }); expect(wrapper.find(.van-password-input__error-info).html()).toMatchSnapshot(); });七、主题定制CSS 变量PasswordInput 支持通过 CSS 变量进行主题定制既可以在全局:root下覆盖也可以结合 ConfigProvider 组件 按需配置。完整变量清单如下名称默认值描述--van-password-input-height50px输入框高度--van-password-input-margin0 var(--van-padding-md)输入框外边距--van-password-input-font-size20px明文展示时的字号--van-password-input-radius6px圆角大小--van-password-input-backgroundvar(--van-background-2)格子背景色--van-password-input-info-colorvar(--van-text-color-2)提示文字颜色--van-password-input-info-font-sizevar(--van-font-size-md)提示文字字号--van-password-input-error-info-colorvar(--van-danger-color)错误提示颜色--van-password-input-dot-size10px掩码圆点直径--van-password-input-dot-colorvar(--van-text-color)掩码圆点颜色--van-password-input-text-colorvar(--van-text-color)明文文字颜色--van-password-input-cursor-colorvar(--van-text-color)光标颜色--van-password-input-cursor-width1px光标宽度--van-password-input-cursor-height40%光标高度相对格子高度--van-password-input-cursor-duration1s光标闪烁周期这些变量的默认值定义在 index.less 的:root, :host选择器中变量名与types.ts中导出的PasswordInputThemeVars一一对应。典型用法示例结合 ConfigProvider 实现组件级定制van-config-provider :theme-varsthemeVars van-password-input :valuevalue / /van-config-providerimport { ref } from vue; export default { setup() { const themeVars ref({ passwordInputHeight: 60px, passwordInputDotColor: #1989fa, passwordInputCursorColor: #1989fa, passwordInputErrorInfoColor: #ee0a24, }); return { themeVars }; }, };注意通过 ConfigProvider 传入主题变量时键名需去掉--van-前缀并转驼峰如--van-password-input-height→passwordInputHeight。八、完整 Demo 参考如果你想查看 PasswordInput 与 NumberKeyboard 联动的完整可运行示例可以直接阅读官方 demo 源码 packages/vant/src/password-input/demo/index.vue。该文件演示了如何用同一套状态管理多个输入场景通过refMap记录各场景的组件实例、用current标记当前聚焦场景、由onInput/onDelete统一处理键盘输入并做 4/6 位长度截断是学习多输入框 单键盘架构的绝佳范本const onInput (key: ValueKeys) { if (!current.value) return; const maxlength current.value customLength ? 4 : 6; const newValue (values.value[current.value] key).slice(0, maxlength); values.value[current.value] newValue; // 满 6 位且非正确密码时展示错误提示 if (current.value showInfo newValue.length 6 newValue ! 123456) { errorInfo.value t(errorInfo); } };结语PasswordInput 通过展示层与输入层解耦的架构将密码输入场景的渲染、交互、校验与主题定制完整地封装为一个 API 极简的组件7 个 Props、1 个事件配合 NumberKeyboard 即可快速落地支付密码、短信验证码等移动端业务。理解其touchstart触发focus、mask位占位渲染、focused光标定位等源码细节能帮助你在二次开发或排查问题时更加得心应手。【免费下载链接】vantA lightweight, customizable Vue UI library for mobile web apps.项目地址: https://gitcode.com/GitHub_Trending/va/vant创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
上一篇/下一篇内容由系统自动关联 返回资讯列表 →