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)
          }
        }
      });
    },
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容