全网最简单的验证码输入框

时间:2019-11-08
本文章向大家介绍全网最简单的验证码输入框,主要包括全网最简单的验证码输入框使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

先上图


要实现一个类似于这样的输入框,而且有几个页面都需要类似的输入框(输入身份证后四位/输入支付密码),就准备撸一个小组件。

# 原理
在一个输入框中输入一串字符串,然后根据下标index分别填入框里,为了代码的可读性,我这里框就用ul,li来写
## 子组件

<template>
<div>
<label for="code">
<ul class="code-box">
<li class="code-number" v-for="(item, index) in length" :key="index">
{{ code[index] }}
</li>
</ul>
</label>
<input
class="code-input"
v-model="code"
:maxlength="length"
type="number"
id="code"
@keyup.13="next()"
/>
</div>
</template>

<script>
export default {
name: "CodeInput",
props: {
length: {
type: Number,
default: 6
}
},
data() {
return {
code: ""
};
},
methods: {
getCode() {
return this.code;
},
next() {
this.$emit("func", this.code);
}
}
};
</script>
<style scoped>
.code-box {
border-radius: 8px;
border: 1px solid #cccccc;
display: inline-flex;
}
.code-number {
width: 56px;
height: 58px;
border-right: solid #cccccc 1px;
text-align: center;
font-size: 30px;
color: red;
}
.code-number:last-child {
border-right: 0;
}
.code-input {
height: 0.44rem;
position: fixed;
outline: none;
color: transparent;
text-shadow: 0 0 0 transparent;
width: 300%;
margin-left: 100%;
}
button {
width: 100px;
height: 60px;
}
</style>

## 父组件

<template>
<div>
<security-code v-model="code" v-on:func="show"></security-code>
</div>
</template>
<script>
import securityCode from "../components/password";
export default {
components: { securityCode },
data() {
return {
code: ""
};
},
methods: {
show() {
console.log(this.code);
this.$router.push({ path: "/" });
}
}
};
</script>
<style lang="less" scoped></style>

# 注意点
1.label属性:html的label属性可以根据input的id扩大input的点击面积。

2.@keyup.13="next()":这一句是指手机键盘的回车/确定/前进键触发 的事件

3.子组件input的位置:我是通过绝对定位使他不在我可视位置上,不能让他display:none

附加:因为一般父子组件的style都是设置了scoped,如果想对设置了scoped的子组件里的元素进行控制可以使用 ’>>>’ 或者 ’deep’,这个自己百度很多方法

原文地址:https://www.cnblogs.com/dcj2018/p/11819342.html