vue 登录验证码自动focus到下一位

做项目时遇见了一个需求是邮箱验证码登录,并且自动聚焦到下一位,删除的时候也会自动聚焦到上一位,如图:


image.png

这边使用的是quasar 框架,看了网上很多的验证码方法都是使用的keydown,keyup方法来触发事件,但是在移动端不起作用,所以这边使用了input方法

<div class="input-main"><div v-for="(item,index) in securityCodeList" :key="index" >
        <q-input oninput="this.value=this.value.replace(/\D/g,'');"
            pattern="[0-9]*" outlined v-model="item.val" maxlength="1" :id="index" class="border-input" @input="nextFocus($event,index)"></q-input>
      </div>

js代码

   nextFocus(el,index) {
      var dom = document.getElementsByClassName("border-input"),
        currInput = dom[index],
        nextInput = dom[index + 1],
        lastInput = dom[index - 1];
      if (el.keyCode != 8) {
         if (index < (this.securityCodeList.length - 1) && el != "") {
            nextInput.focus();
        } else {
         currInput.blur();
            if(index != 0 ){
                if(el == ""){
                  this.securityCodeList[index].val = "";
                  lastInput.focus();
                  }
            }
        }
      }else{
        if (index !=0) {
          lastInput.focus();
                       }
      }
    let code = ""
   this.securityCodeList.forEach(item =>{
       code += item.val
    })
    if(code.length === 4){
        const params = {
         captcha: code
    }
    setEmailNumber(params).then(res =>{
            // console.log(res)
             if(res.code === "200"){
        const sessionKey = res.data;
            // this.getToken(sessionKey);
             localStorage.setItem("token", sessionKey);
            this.getInfo();
    }
          }).catch(error=>{
            if(error.response.data.msg === "wrong captcha!"){
              this.showTipText = true
            }
          })
    }
  },

如果需要有倒计时和再次触发的需求,可以参考下方代码

 submitEmail() {
      this.$refs.email.validate().then(async success => {
        if (success) {
          const sendRes = await sendEmailReq({
            email: this.email.trim(),
            expire: true
          });
          if (sendRes.code === "200") {
       this.TimeValue =120
      this.clock =  window.setInterval(() => {
        this.TimeValue -= 1;
        this.openMagic();
        this.TimeValue 
        if (this.TimeValue === 0) {  
         window.clearInterval(this.clock)
         this.sendStatus = false
          }
      },1000)
          }
        }
      });
    },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容