vue实现一个6个输入框的验证码输入组件功能的实例代码


Posted in Javascript onJune 29, 2020

vue实现一个6个输入框的验证码输入组件功能的实例代码

要实现的功能:

完全和单输入框一样的操作,甚至可以插入覆盖:

1,限制输入数字

2,正常输入

3,backspace删除

4,paste任意位置粘贴输入

5,光标选中一个数字,滚轮可以微调数字大小,限制0-9

6,123|456 自动覆盖光标后输入的字符,此时光标在3后,继续输入111,会得到123111,而不用手动删除456

7,封装成vue单文件组件,方便任意调用。

模板代码

<template>
  <div class="input-box">
    <div class="input-content" @keydown="keydown" @keyup="keyup" @paste="paste" @mousewheel="mousewheel"
        @input="inputEvent">
      <input max="9" min="0" maxlength="1" data-index="0" v-model.trim.number="input[0]" type="number"
          ref="firstinput"/>
      <input max="9" min="0" maxlength="1" data-index="1" v-model.trim.number="input[1]" type="number"/>
      <input max="9" min="0" maxlength="1" data-index="2" v-model.trim.number="input[2]" type="number"/>
      <input 
      <input max="9" min="0" maxlength="1" data-index="4" v-model.trim.number="input[4]" type="number"/>
      <input max="9" min="0" maxlength="1" data-index="5" v-model.trim.number="input[5]" type="number"/>
    </div>
  </div>
</template>

实现了键盘的keydown/keyup/paste/input和鼠标滚轮mousewheel事件

使用了6个输入框的方案来实现。

样式部分:使用了scss模式

<style scoped lang="scss">
  .input-box {
    .input-content {
      width: 512px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      input {
        color: inherit;
        font-family: inherit;
        border: 0;
        outline: 0;
        border-bottom: 1px solid #919191;
        height: 60px;
        width: 60px;
        font-size: 44px;
        text-align: center;
      }
    }
    
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      appearance: none;
      margin: 0;
    }
  }
</style>

具体实现逻辑:主要实现以上几个键盘事件操作。

<script>
  export default {
    data() {
      return {
        // 存放粘贴进来的数字
        pasteResult: [],
      };
    },
    props: ['code'],
    computed: {
      input() {
        // code 是父组件传进来的默认值,必须是6位长度的数组,这里就不再做容错判断处理
        // 最后空数组是默认值
        return this.code || this.pasteResult.length === 6 ? this.pasteResult : ['', '', '', '', '', '']
      }
    },
    methods: {
      // 解决一个输入框输入多个字符
      inputEvent(e) {
        var index = e.target.dataset.index * 1;
        var el = e.target;
        this.$set(this.input, index, el.value.slice(0, 1))
      },
      keydown(e) {
        var index = e.target.dataset.index * 1;
        var el = e.target;
        if (e.key === 'Backspace') {
          if (this.input[index].length > 0) {
            this.$set(this.input, index, '')
          } else {
            if (el.previousElementSibling) {
              el.previousElementSibling.focus()
              this.$set(this.input, index - 1, '')
            }
          }
        } else if (e.key === 'Delete') {
          if (this.input[index].length > 0) {
            this.$set(this.input, index, '')
          } else {
            if (el.nextElementSibling) {
              this.$set(this.input, index = 1, '')
            }
          }
          if (el.nextElementSibling) {
            el.nextElementSibling.focus()
          }
        } else if (e.key === 'Home') {
          el.parentElement.children[0] && el.parentElement.children[0].focus()
        } else if (e.key === 'End') {
          el.parentElement.children[this.input.length - 1] && el.parentElement.children[this.input.length - 1].focus()
        } else if (e.key === 'ArrowLeft') {
          if (el.previousElementSibling) {
            el.previousElementSibling.focus()
          }
        } else if (e.key === 'ArrowRight') {
          if (el.nextElementSibling) {
            el.nextElementSibling.focus()
          }
        } else if (e.key === 'ArrowUp') {
          if (this.input[index] * 1 < 9) {
            this.$set(this.input, index, (this.input[index] * 1 + 1).toString());
          }
        } else if (e.key === 'ArrowDown') {
          if (this.input[index] * 1 > 0) {
            this.$set(this.input, index, (this.input[index] * 1 - 1).toString());
          }
        }
      },
      keyup(e) {
        var index = e.target.dataset.index * 1;
        var el = e.target;
        if (/Digit|Numpad/i.test(e.code)) {
          this.$set(this.input, index, e.code.replace(/Digit|Numpad/i, ''));
          el.nextElementSibling && el.nextElementSibling.focus();
          if (index === 5) {
            if (this.input.join('').length === 6) {
              document.activeElement.blur();
              this.$emit('complete', this.input);
            }
          }
        } else {
          if (this.input[index] === '') {
            this.$set(this.input, index, '');
          }
        }
      },
      mousewheel(e) {
        var index = e.target.dataset.index;
        if (e.wheelDelta > 0) {
          if (this.input[index] * 1 < 9) {
            this.$set(this.input, index, (this.input[index] * 1 + 1).toString());
          }
        } else if (e.wheelDelta < 0) {
          if (this.input[index] * 1 > 0) {
            this.$set(this.input, index, (this.input[index] * 1 - 1).toString());
          }
        } else if (e.key === 'Enter') {
          if (this.input.join('').length === 6) {
            document.activeElement.blur();
            this.$emit('complete', this.input);
          }
        }
      },
      paste(e) {
        // 当进行粘贴时
        e.clipboardData.items[0].getAsString(str => {
          if (str.toString().length === 6) {
            this.pasteResult = str.split('');
            document.activeElement.blur();
            this.$emit('complete', this.input);
          }
        })
      }
    },
    mounted() {
      // 等待dom渲染完成,在执行focus,否则无法获取到焦点
      this.$nextTick(() => {
        this.$refs.firstinput.focus()
      })
    },
  }
</script>

如果你发现了bug,或者有优化空间,欢迎你的指正和建议。我会随时更新到原代码当中,分享给大家。

到此这篇关于vue实现一个6个输入框的验证码输入组件的文章就介绍到这了,更多相关vue实现输入框的验证码输入组件内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Javascript 相关文章推荐
createElement动态创建HTML对象脚本代码
Nov 24 Javascript
js原型继承的两种方法对比介绍
Mar 30 Javascript
Javascript基于AJAX回调函数传递参数实例分析
Dec 15 Javascript
js调出上下文菜单的实例
Dec 17 Javascript
JavaScript的setter与getter方法
Nov 29 Javascript
微信小程序实现简单input正则表达式验证功能示例
Nov 30 Javascript
微信小程序实现自定义加载图标功能
Jul 19 Javascript
微信小程序中使用wxss加载图片并实现动画效果
Aug 13 Javascript
使用gulp构建前端自动化的方法示例
Dec 25 Javascript
微信小程序表单验证插件WxValidate的二次封装功能(终极版)
Sep 03 Javascript
用JS实现一个简单的打砖块游戏
Dec 11 Javascript
webpack+vue-cil 中proxyTable配置接口地址代理操作
Jul 18 Javascript
纯JS开发baguetteBox.js响应式画廊插件
Jun 28 #Javascript
JavaScript图片旋转效果实现方法详解
Jun 28 #Javascript
javascript+css实现俄罗斯方块小游戏
Jun 28 #Javascript
详解小程序横屏方案对比
Jun 28 #Javascript
微信小程序实现上传多张图片、删除图片
Jul 29 #Javascript
js模拟实现百度搜索
Jun 28 #Javascript
微信小程序地图实现展示线路
Jul 29 #Javascript
You might like
完美实现wordpress禁止文章修订和自动保存的方法
2014/11/03 PHP
php保存任意网络图片到服务器的方法
2015/04/14 PHP
YII2框架中actions的作用与使用方法示例
2020/03/13 PHP
yii2.0框架多模型操作示例【添加/修改/删除】
2020/04/13 PHP
浅说js变量
2011/05/25 Javascript
跟我学Nodejs(三)--- Node.js模块
2014/05/25 NodeJs
jQuery之DOM对象和jQuery对象的转换与区别分析
2015/01/08 Javascript
JS实现浏览器状态栏显示时间的方法
2015/10/27 Javascript
Vue.js实现的计算器功能完整示例
2018/07/11 Javascript
vue 界面刷新数据被清除 localStorage的使用详解
2018/09/16 Javascript
bootstrap-table formatter 使用vue组件的方法
2019/05/09 Javascript
在vue中使用防抖和节流,防止重复点击或重复上拉加载实例
2019/11/13 Javascript
重置Redux的状态数据的方法实现
2019/11/18 Javascript
js生成1到100的随机数最简单的实现方法
2020/02/07 Javascript
vue+高德地图实现地图搜索及点击定位操作
2020/09/09 Javascript
浅析Python中else语句块的使用技巧
2016/06/16 Python
详解Python中的相对导入和绝对导入
2017/01/06 Python
python 使用 requests 模块发送http请求 的方法
2018/12/09 Python
pyqt远程批量执行Linux命令程序的方法
2019/02/14 Python
快速排序的四种python实现(推荐)
2019/04/03 Python
PyInstaller将Python文件打包为exe后如何反编译(破解源码)以及防止反编译
2020/04/15 Python
python字符串拼接+和join的区别详解
2020/12/03 Python
Python try except finally资源回收的实现
2021/01/25 Python
HTML5 自动聚焦(autofocus)属性使用介绍
2013/08/07 HTML / CSS
使用数据结构给女朋友写个Html5走迷宫游戏
2019/11/26 HTML / CSS
西班牙多品牌鞋店连锁店:Krack
2018/11/30 全球购物
法国二手MacBook销售网站:Okamac
2019/03/18 全球购物
Skechers越南官方网站:来自美国的运动休闲品牌
2021/02/22 全球购物
销售副总经理岗位职责
2013/12/11 职场文书
环境保护建议书
2014/08/26 职场文书
党支部组织生活会整改方案
2014/09/30 职场文书
会计主管竞聘书
2015/09/15 职场文书
2016班级元旦联欢会开幕词
2016/03/04 职场文书
python爬取企查查企业信息之selenium自动模拟登录企查查
2021/04/08 Python
深入浅出的讲解:信号调制到底是如何实现的
2022/02/18 无线电
利用Python将list列表写入文件并读取的方法汇总
2022/03/25 Python