In my Vue.js component for 2FA, I have implemented the following structure:
<template>
<div :class="onwhite ? 'on-white' : ''">
<input
:id="`n1`"
ref="n1"
v-model="i1"
class="input-two-fa center"
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"
class="input-two-fa center"
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"
class="input-two-fa center"
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>
I aim to shift the focus to the previous input field when a user presses the delete button on the keyboard, even if no input has been entered. The issue arises in the handleDeleteClick
function, where despite accessing the element using this.$refs[ref]
, attempts to proceed result in an undefined error.
Despite trying to incorporate a this.$nextTick
callback, the solution did not materialize. Can you identify the underlying problem here?
PS: The representation of only 3 fields for 2FA is solely for exemplification purposes.