vue实现支付密码框
Vue 实现支付密码框
使用基础输入框组件
创建一个基础的输入框组件,限制输入类型为密码,并设置最大长度。通过v-model绑定数据,监听输入变化。
<template>
<input
type="password"
v-model="password"
maxlength="6"
@input="handleInput"
/>
</template>
<script>
export default {
data() {
return {
password: ''
}
},
methods: {
handleInput() {
this.$emit('update:password', this.password)
}
}
}
</script>
实现六位密码框
将密码框拆分为六个独立的输入框,每个输入框只允许输入一个字符。通过ref聚焦到下一个输入框。
<template>
<div class="password-box">
<input
v-for="(item, index) in digits"
:key="index"
ref="inputs"
type="password"
v-model="digits[index]"
maxlength="1"
@input="moveFocus(index)"
/>
</div>
</template>
<script>
export default {
data() {
return {
digits: ['', '', '', '', '', '']
}
},
methods: {
moveFocus(index) {
if (this.digits[index] && index < 5) {
this.$refs.inputs[index + 1].focus()
}
this.$emit('update:password', this.digits.join(''))
}
}
}
</script>
添加样式优化
为密码框添加样式,使其看起来更像一个连贯的密码输入区域。

.password-box {
display: flex;
gap: 10px;
}
.password-box input {
width: 40px;
height: 50px;
text-align: center;
font-size: 20px;
border: 1px solid #ccc;
border-radius: 4px;
}
处理键盘事件
监听键盘事件,允许用户通过退格键删除输入并聚焦到上一个输入框。
<template>
<input
@keydown.delete="handleDelete(index)"
/>
</template>
<script>
methods: {
handleDelete(index) {
if (!this.digits[index] && index > 0) {
this.$refs.inputs[index - 1].focus()
}
}
}
</script>
集成到支付页面
将密码框组件集成到支付页面,监听密码输入完成事件。

<template>
<PasswordBox @update:password="handlePasswordUpdate" />
</template>
<script>
import PasswordBox from './PasswordBox.vue'
export default {
components: {
PasswordBox
},
methods: {
handlePasswordUpdate(password) {
if (password.length === 6) {
this.submitPayment(password)
}
}
}
}
</script>
添加输入验证
在提交支付前验证密码是否符合要求,如是否为纯数字。
methods: {
submitPayment(password) {
if (!/^\d{6}$/.test(password)) {
alert('请输入6位数字密码')
return
}
// 调用支付接口
}
}
实现密码隐藏与显示
添加一个切换按钮,允许用户临时显示密码。
<template>
<button @click="toggleShow">{{ showPassword ? '隐藏' : '显示' }}</button>
<input :type="showPassword ? 'text' : 'password'" />
</template>
<script>
export default {
data() {
return {
showPassword: false
}
},
methods: {
toggleShow() {
this.showPassword = !this.showPassword
}
}
}
</script>






