先来看波完成效果图
输入 4 位或 6 位短信验证码,输入完成后收起键盘
布局排版
- class="security-code-wrap">
- for="code">
- class="security-code-container">
- class="field-wrap" v-for="(item, index) in number" :key="index">
- class="char-field">{{value[index] || placeholder}}
- ref="input" class="input-code" @keyup="handleInput($event)" v-model="value"
- id="code" name="code" type="tel" :maxlength="number"
- autocorrect="off" autocomplete="off" autocapitalize="off">
隐藏输入框
- .input - code {
- position: absolute;
- left: -9999px;
- top: -99999px;
- width: 0;
- height: 0;
- opacity: 0;
- overflow: visible;
- z - index: -1;
- }
处理验证码输入
- handleSubmit() {
- this.$emit('input', this.value)
- },
- handleInput(e) {
- this.$refs.input.value = this.value
- if (this.value.length >= this.number) {
- this.hideKeyboard()
- }
- this.handleSubmit()
- }
完成输入后关闭虚拟键盘
- hideKeyboard() {
- // 输入完成隐藏键盘
- document.activeElement.blur() // ios隐藏键盘
- this.$refs.input.blur() // android隐藏键盘
- }
- class="security-code-wrap">
- for="code">
- class="security-code-container">
- class="field-wrap" v-for="(item, index) in number" :key="index">
- class="char-field">{{value[index] || placeholder}}
- ref="input" class="input-code" @keyup="handleInput($event)" v-model="value"
- id="code" name="code" type="tel" :maxlength="number"
- autocorrect="off" autocomplete="off" autocapitalize="off">
- export default {
- name: 'SecurityCode',
- // component properties
- props: {
- number: {
- type: Number,
- default: 4
- },
- placeholder: {
- type: String,
- default: '-'
- }
- },
- // variables
- data() {
- return {
- value: ''
- }
- },
- methods: {
- hideKeyboard() {
- // 输入完成隐藏键盘
- document.activeElement.blur() // ios隐藏键盘
- this.$refs.input.blur() // android隐藏键盘
- },
- handleSubmit() {
- this.$emit('input', this.value)
- },
- handleInput(e) {
- this.$refs.input.value = this.value
- if (this.value.length >= this.number) {
- this.hideKeyboard()
- }
- this.handleSubmit()
- }
- }
- }
- scoped lang="less">
- .security-code-wrap {
- overflow: hidden;
- }
- .security-code-container {
- margin: 0;
- padding: 0;
- display: flex;
- justify-content: center;
- .field-wrap {
- list-style: none;
- display: block;
- width: 40px;
- height: 40px;
- line-height: 40px;
- font-size: 16px;
- background-color: #fff;
- margin: 2px;
- color: #000;
- .char-field {
- font-style: normal;
- }
- }
- }
- .input-code {
- position: absolute;
- left: -9999px;
- top: -99999px;
- width: 0;
- height: 0;
- opacity: 0;
- overflow: visible;
- z-index: -1;
- }
- v-model="authCode">
怎么样,484 so easy
一开始的思路也是 4 个输入框,监听输入完成跳到下一个输入框,这样的做法也能达到目的,不过需要更多的代码去维护这个规则,不够优雅。
目前的做法已经是我能想到最优的解决方案,如果你有更好的实现思路,还望不吝赐教。
来源: https://juejin.im/post/5a31ddb251882527541053ee