Tips for assigning focus properties inside VueJS components

Within my component child Input:

<template>
  <div class="basic-input-outer" :style="styles">
    <p class="paragraph-small">{{ title }}</p>
    <input ref="name" :type="type" class="basic-input">
  </div>
</template>

<script>
export default {
  name: "Input",
  props: ['type', 'styles', 'title', 'focus'],
  watch: {
    focus: function() {
      this.setFocus()
    }
  },
  methods: {
    setFocus() {
      this.$refs.name.focus()
    }
  }
}
</script>

<style lang="scss">
@import "../assets/css/components/Input";
</style>

In addition, I have a parent component where I interact with this input:

   <div class="login-options">
     <p class="choose" @click="chooseLogin('email')">With Email</p>
     <div class="vertical-line" />
     <p class="choose" @click="chooseLogin('phone')">With Phone Number</p>
   </div>

   <div v-if="loginWithEmail">
    <Input :focus="emailFocus" :title="'Email'" :type="'email'" />
   </div>
   <div v-else>
     <Input :focus="phoneFocus" :title="'Phone number'" :type="'email'" />
   </div>

...

chooseLogin(option) {
  if (option === 'email') {
    this.loginWithEmail = true
    this.emailFocus = true
  } else {
    this.loginWithEmail = false
    this.phoneFocus = true
  }
}

The issue I am facing is that when I trigger the function, it only focuses on one field once and then stops. I want to enhance the functionality of the focus prop so that when triggered, the field will be focused and continue to work multiple times, rather than just once as in its current state.

Answer №1

The solution is found! The issue stemmed from the use of v-if. When using v-if, the element(s) are simply removed from the DOM. To overcome such problems, it is recommended to implement conditional styling using display: none.

Here's an example of how to do this:

<template>
  <div class="basic-input-outer" :style="styles">
    <p class="paragraph-small">{{ title }}</p>
    <input ref="name" :type="type" class="basic-input">
  </div>
</template>

<script>
export default {
  name: "Input",
  props: ['type', 'styles', 'title', 'focus'],
  watch: {
    focus: function() {
      if (this.focus) this.$refs.name.focus()
    }
  }
}
</script>

<style lang="scss">
@import "../assets/css/components/Input";
</style>

Additionally, in the parent component:

<Input :style="[!loginWithEmail ? {'display': 'none'} : {'': ''}]" :focus="emailFocus" :title="'Email'" :type="'email'" />
<Input :style="[loginWithEmail ? {'display': 'none'} : {'': ''}]" :focus="phoneFocus" :title="'Phone number'" :type="'email'" />

...

    chooseLogin(option) {
      if (option === 'email') {
        this.loginWithEmail = true
        this.emailFocus = true
        this.phoneFocus = false
      } else {
        this.loginWithEmail = false
        this.emailFocus = false
        this.phoneFocus = true
      }
    }

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

Error: The function "text.toLowerCase()" is not defined

Whenever I execute the following code, I keep encountering this error message: Uncaught TypeError: text.toLowerCase is not a function const getVisibleExpenses = (expenses, { text, sortBy, startDate, endDate }) => { return expenses.fi ...

Difficulty in managing vertical overflow in a dynamically sized table using Bootstrap

I am facing an issue with the table-responsive class that is causing a scroll on the y-axis even though it is not specified in the CSS. Shown below is a screenshot of the problem, and I have also managed to replicate the bug: <div id="app"> <d ...

Node.js npm-migration enables the creation of multiple tables in a single migration process

I am new to npm-migration for nodejs and I am exploring ways to streamline the process of creating multiple tables using a single migration, rather than having separate migrations for each table creation. I have experimented with the following code: "up": ...

Troubleshooting the Nextjs-blog tutorial loading issue on localhost:3000

Looking to delve into Nextjs, I decided to start by following a tutorial. However, every time I attempt to run 'npm run dev', the local host just keeps loading endlessly. Upon inspecting and checking the console, there is no feedback whatsoever. ...

CoffeeScript's alert feature appears to be malfunctioning

After stumbling upon CoffeeScript in a blog post, I was excited to try it out. My first attempt at using it involved this code snippet: alert "Hello CoffeeScript!" Unfortunately, it didn't work as expected and produced the following error message: ...

JS: I'm struggling to understand the scope

I've been working on adapting CouchDB's JS API to function asynchronously, but I'm encountering an unresolved error: You can find my version of the JS API here on Pastebin. Whenever I execute (new CouchDB("dbname")).allDocs(function(result) ...

After a postback in JavaScript, the Root Path variable becomes null

I have been attempting to save the Root URL in a JavaScript variable within my _Layout.cshtml like this: <script type="text/javascript> var rootpath = ""; $(document).ready(function () { rootpath = "@VirtualPathUtility.ToAbsolute("~/ ...

Why is the function not being invoked in Ext JS?

Ext.define('iTell.view.MarketView', { extend: 'Ext.Container', xtype: 'marketview', config: { scrollable: false, layout: 'fit', items: [ { xtype: &apos ...

Display the footer once the user has reached the end of the page by scrolling

Below is the footer code I am working with. <div class="row"> <div class="col-md-12"> <div> this section always remains at the bottom </div> </div> <div class="col-md-12"> <div> only v ...

Submitting the form does not result in the textbox being cleared

I have been attempting to clear the txtSubTotal text box upon clicking the PROCEED button, but it seems that my efforts have been in vain despite trying various code examples, including those from SO. btnProceed/HTML <input type="submit" name="btnProc ...

Detecting file changes in ExpressJS after writing data to a file.This

I'm facing an issue with my endpoints. One endpoint is responsible for writing JSON data to a static file, while another endpoint is supposed to retrieve and send that data. The problem arises when I make changes to the file but the endpoint still sen ...

Conserving node.js native imports for Electron with rollup

I am working on a project using Electron, Svelte, and Typescript. Initially, I used a specific template from here, but it restricted access to node.js built-in imports like fs for security reasons in the browser/electron frontend. However, I do not requir ...

Prevent IonContent from scrolling to the bottom or top when using Ionic framework

In my Ionic app, I have a long text page with 2 buttons that trigger the actions scrollToBottom and scrollToTop. Due to the length of the page, I have set the scroll duration to be 30 seconds. I am facing two issues here: How can I stop the scrolling ...

steps to remove the border of the select box in MUI component

i am struggling to disable the border on the select box and change the color of the label text when focused or blurred i have attempted it but have been unsuccessful i am not very skilled at Mui component customization this is the image that i desire ht ...

Can arrays be passed as function parameters in CrossRider without the need to convert them into objects first?

Our team is currently utilizing CrossRider to develop an extension specifically for Internet Explorer. We have a crucial object that is downloaded from , but we are facing an issue where arrays within this object are getting converted into objects with int ...

Discover a method to receive an alert when the mouse exits the inner window along the y-axis

Is there a way to receive an alert if the mouse moves out of the inner window solely in the y-axis? Currently, alerts are triggered when the mouse moves out on both x-axis and y-axis. For example, if the mouse pointer hovers over the address bar coming fro ...

The Vuetify theme seems to be getting overlooked

I recently created a file in my plugins directory with the following code snippet: import Vue from "vue"; import Vuetify from "vuetify/lib/framework"; Vue.use(Vuetify); export default new Vuetify({ theme: { themes: { light ...

The conventional method for including React import statements

I'm curious if there is a standard convention for writing import statements in React. For instance, I currently have the following: import React, { useState, FormEvent } from 'react'; import Avatar from '@material-ui/core/Avatar'; ...

Iframes are not compatible with JQuery UI dialogs

After attempting to open a URL within an Iframe in a JQuery dialog box, I encountered the following issue: Here is the code snippet that I used: http://pastebin.com/Wqf0mGhZ I am looking for a solution to make sure that the dialog displays all of the con ...

HTML code now launches in the existing electron window rather than opening a new window

<html> <head> <title></title> </head> <input type="button" name="new" id="newmon" value="new"> <button onclick="open1()">monitor 1</button&g ...