- 模拟密码框
- num:有多少位 Number 默认6位
- inputsize:输入框正方形大小 Number 默认值30
- inputRight: 输入框右边距 Number 默认值20
- inputBottom: 输入框下边距 Number 默认值20
- lineNum:一行几个 Number 默认值:6
- type:类型 String 默认值text,可以选择password
<template>
<div>
<div class="box" :style="{width:lineNum*(inputsize+inputRight)+'px'}">
<input :type="type" v-for="i in num" :key="i" v-model="arr[i-1]" class="box-input" maxlength="1"
:style="{width:inputsize+'px',height:inputsize+'px',lineHeight:inputsize+'px', marginBottom: inputBottom+'px',marginRight:inputRight+'px'}">
</div>
<button @click="commit">提交</button>
</div>
</template>
<script>
export default {
props:{
num:{
type:Number,
default:6
},
inputsize:{
type:Number,
default:30
},
inputRight:{
type:Number,
default:20
},
inputBottom:{
type:Number,
default:20
},
lineNum:{
type:Number,
default:6
},
type:{
type:String,
default:'text'
}
},
data(){
return{
arr:new Array(this.num),
current:0
}
},
mounted(){
this.nextInput()
for(let i=0;i<this.arr.length;i++){
this.arr[i]=''
}
},
methods:{
nextInput(){
let inputs = document.querySelectorAll('.box-input')
for(let i=0;i<inputs.length;i++){
let input = inputs[i]
input.index=i;
input.onkeyup=function(e){
let up=this.index-1
if(e.keyCode===8 && input.value===''){
if(up<0||this.index==0) return ;
inputs[up].focus()
}
if(!/^[0-9a-zA-Z]+$/.test(input.value)) return input.value='';
let code=e.keyCode
if(code<48||(code>57&&code<65)||(code>90&&code<96)||(code>105)) return ;
let next=this.index+1;
input.value=e.key
if(next>inputs.length-1) return;
inputs[next].focus()
}
}
},
commit(){
let str='';
for(let i=0;i<this.num;i++){
console.log(this.arr[i]);
if(this.arr[i]==''){
str+='-'
}else{
str+=this.arr[i]
}
}
this.$emit('commit',str)
}
}
}
</script>
<style lang="less">
.box{
margin: 0;
.box-input{
box-sizing: border-box;
text-align: center;
}
}
</style>
测试用例
<template>
<passwordInto type="password" :num="20" :lineNum="10" @commit="commit"/>
</template>
<script>
import passwordInto from '@/components/passwordInto.vue'
export default {
components:{
passwordInto
},
methods:{
commit(val){
console.log(val);
}
}
</script>
|