Home > Enterprise >  How to focus on input element using ref name in Vue.js
How to focus on input element using ref name in Vue.js

Time:07-15

I have Vue.js component for 2FA.

Here is how it looks like:

<template>
  <div :>
    <input
      :id="`n1`"
      ref="n1"
      v-model="i1"
      
      type="number"
      :disabled="disabled"
      min="0"
      max="9"
      autocomplete="off"
      autofocus
      oninput="
      if (this.value === '') {
        if (this.previousElementSibling) {
          this.previousElementSibling.focus()
        }
      } else {
        this.nextElementSibling.focus()
      }"
    >
    <input
      :id="`n2`"
      ref="n2"
      v-model="i2"
      
      type="number"
      :disabled="disabled"
      min="0"
      max="9"
      autocomplete="off"
      autofocus
      oninput="
      if (this.value === '') {
        this.previousElementSibling.focus()
      } else {
        this.nextElementSibling.focus()
      }"
      @keyup.delete="handleDeleteClick('n1')"
    >
    <input
      :id="`n3`"
      ref="n3"
      v-model="i3"
      
      type="number"
      :disabled="disabled"
      min="0"
      max="9"
      autocomplete="off"
      autofocus
      oninput="
      if (this.value === '') {
        this.previousElementSibling.focus()
      } else {
        this.nextElementSibling.focus()
      }"
      @keyup.delete="handleDeleteClick('n2')"
    >
  </div>
</template>

<script>
import { validate2fa } from "~/helpers/frontValidator";
export default {
  name: "InputTwoFa",
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    onwhite: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      i1: '', i2: '', i3: '',
      twoFaCode: ['', '', '']
    }
  },
  watch: {
    i1() { this.i1 = validate2fa(this.i1); this.twoFaCode[0] = this.i1; this.returnTwoFa() },
    i2() { this.i2 = validate2fa(this.i2); this.twoFaCode[1] = this.i2; this.returnTwoFa() },
    i3() { this.i3 = validate2fa(this.i3); this.twoFaCode[2] = this.i3; this.returnTwoFa() },
  },
  methods: {
    returnTwoFa() {
      this.$emit('returnTwoFa', this.twoFaCode)
    },
    handleDeleteClick(ref) {
      const elem = this.$refs[ref]
      console.log(elem) // There is element here
      // this.$refs[ref].$el.focus() - undefined
    }
  }
}
</script>

What I want to do is when user presses delete button on keyboard (even if he hasn't provided anything) focus on previous input field.

The problem is in handleDeleteClick function. Using this.$refs[ref] I can get the element, but then, no matter what I use, I get undefined error.

I was trying to use this.$nextTick callback, but it didn't work, so, what's the problem?

PS Only 3 fields for 2FA is just for example.

CodePudding user response:

No need to use the $el property :

this.$refs[ref].focus() 

  • Related