Tips on using the ref attribute in Vue.js to focus on an input element

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.

Answer №1

Avoid using the $el attribute in this scenario:

this.$refs[ref].focus()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular JS Sorting Wordpress Plugin allows users to easily organize and sort content

Seeking some assistance here, any help would be greatly appreciated. Currently using a Wordpress Angular JS plugin that is causing some unusual alphabetical sorting. This snippet of code showcases the taxonomy: <!-- for taxonomy --> <div ng-if ...

I keep seeing props displaying as $attrs in the VUE DevTools

click here for image descriptioncheck out this other image I am facing an issue where my props are displaying as $attrs in VUE DEV TOOLS. I attempted to resolve the problem by disabling attrs using inheritAttrs: false and v-bind="$attrs", but it did not ...

Cutting imagery to create a new design element

https://i.sstatic.net/IAh0h.jpg There is an image above with 6 gears (circles with pointy edges). My goal is to separate them into individual pictures and, on each picture's hover, have a relevant line with text appear. How can I achieve this? The a ...

Unable to push information to an Azure SQL Database through Azure Functions

I am facing an issue where I need to add new rows to my Azure SQL Database using an Azure Function. The specific error message that I am encountering is RequestError: Cannot insert the value NULL into column 'OrgName', table 'ICTDatabase.d ...

Unable to modify the properties of a stateless child component

I'm completely new to React and I decided to create a basic comments application. My main objective was to let users change their display pictures by clicking the 'Change Avatar' button. https://i.sstatic.net/TqVe4.png However, I encountere ...

Retrieve a JSON response from within a schema housed in MongoDB

I have a document structure that looks like this: { "id": "someString", "servers": [ { "name": "ServerName", "bases": [ { "name": "Base 1", "status": true }, { "name": "Base 2", ...

Implementing dynamic component swapping in Vue 3 using components from another component

I currently have a display component called app-display, which contains a dynamic component inside (by default, it is set to app-empty): app.component('appDisplay', { template: `<component :is="currentComponent"></c ...

Steps for transforming a JSON into a Class to generate objects

My JSON data is displayed below: var nodeclienthash={ socket:null, init : function() { // Initializing socket.io this.socket = new io.Socket(this.config.host, {port: this.config.port, rememberTransport: false}); } }; I am currently looking t ...

What is the best way to minimize the number of requests sent in AngularJS?

Currently in my demo, each time a user types something into an input field, a request is sent to the server. However, I would like only one request to be fired. For example, if the user types "abc," it currently fires three requests. Is there a way for the ...

Match the test choices with the corresponding `radio` buttons

Looking for help with my quiz application. How can I align text vertically with radio buttons? Take a look at the code here on Codepen. One issue I'm facing is the alignment of long label texts, particularly in questions 9, 12 & 14. I've tried va ...

Issue with Custom Tooltip in Mootools 1.2 - Images displaying prematurely before hover action

Encountering an issue with Mootools 1.2 Tips (custom tooltips) We are currently utilizing Joomla with the latest update that includes Mootools 1.2, and I am working with the following JS code: $$('.tipz').each(function(element,index) { ...

What is the best way to combine the average hours, minutes, seconds, and milliseconds in JavaScript?

I am seeking guidance on how to calculate the average of three different times in JavaScript. In the scenario presented below, the average of the three times is calculated as 01:42:22:566. <form action="/action_page.php"> <label for= ...

How can you align the label of a v-text-field to the right in rtl languages?

I am working with a v-text-field in the following format: <v-text-field v-model="username" label="نام کاربری" /> However, I have noticed that the label appears on the left side. Is there a way to adjust it so that it displays on the right ...

Google Cloud Platform (GCP) reported a Stripe webhook error stating that no matching signatures were found for the expected signature

Current Stripe version: "8.107.0" I am encountering an issue with Stripe webhook verification whenever I deploy my webhook on Google Cloud Platform (GCP). Despite trying various methods to include the raw body in the signature, including the cod ...

Experiencing problems with web page layout when using bootstrap on IE8?

Here is a code snippet that functions correctly in IE9 and later versions, but encounters issues in IE8: <div class="col-lg-5 col-md-5 col-sm-6 col-xs-6" id="div1"> <div class="panel panel-default" style="" id="panel1"> ...

Create a button toggle feature to dynamically display data for a specific record within an ng-repeat loop

Currently, I am facing an issue while implementing a start and stop timer in JavaScript for a list of records. To display all the items, I am using ng-repeat. Each repeated element has a Start/Stop toggle button. The problem arises when there are 4 records ...

Inserting Random Data into MySQL Tables using Node.js

I am currently working on developing a game bot for Discord similar to Town of Salem, Wolvesville, Feign, and others. Within my database, I have a table called "joinedplayer" which stores users who have used the "join" command: gamerid discordid 1 ...

What is the best way to manually decrease the speed of an object's rotation using javascript?

Can anyone assist me with slowing down the mouse-controlled rotation of a 3D object in javascript? The current rotation is too sensitive and difficult to control manually. Below is the code I am using: <html> <head> <script src="js/thr ...

KnockoutJS's data binding feature is failing to display any content within the table rows

My JavaScript function creates a model and applies it to an HTML document using knockoutJS. In the HTML file, I have two different ways of displaying the same data: 1- A select list (which is working fine) 2- A table (not showing the same data) I need a ...

What could be causing my function to execute thrice?

I cannot seem to figure out why my tag cloud is causing the required function to run multiple times instead of just once when I click on a tag. This issue persists whether using jQuery or plain JavaScript. What am I missing? The code I have is very simple, ...