前言
微信小程序中,要为用户提供安全密码,用于后续的操作。UI设计稿类似微信的安全密码设置,需要两次输入,验证密码一致。之前刚入坑的时候,就收藏了一些小程序相关的好案例,没有前人铺路,也不会有今天的这篇文章。在此特别鸣谢,NAMECZ的博文(https://blog.csdn.net/namecz/article/details/79892451),文章的思路很巧妙。
正文
项目中多次使用到该模块,因此抽象为一个组件(password-box)来实现。通过对外暴露的属性和方法,达到项目需求。以下附上组件源码,给大家一个参考:
wxml:
<view class="password-box">
<view class='password-wrapper'>
<!-- 伪装的input -->
<block wx:for="{
{inputLength}}" wx:key="item">
<!-- 宽高可以由外部指定 -->
<view class="password-item" style="width: {
{inputWidth}}; height: {
{inputHeight}}" catchtap='_focusInput'>
<!-- 隐藏密码时显示的小圆点【自定义】 -->
<view wx:if="{
{!showValue && currentValue.length>=index+1}}" class="hidden"></view>
<!-- 显示密码时显示对应的值 -->
<view wx:if="{
{showValue}}" class="show">{
{currentValue.length>=index+1?currentValue[index]:''}}</view></view>
</block>
</view>
<!-- 隐藏的输入框 -->
<input type="number" password="{
{true}}" value="{
{currentValue}}" class='hidden-input' maxlength="{
{inputLength}}" focus="{
{inputFocus}}" bindinput="_setCurrentValue"></input>
</view>
js: