Utilizing Vue refs to set focus on a specific element target

Clicking on "span class="before-click" should hide it,
and display input class="after-click" instead.
The displayed input must be in focus!
However, when trying to use $refs.afterClick to access the DOM and apply .focus(),
an unexpected error stating that .focus() is not a function occurs.
How can this issue be resolved?
Thank you.

var myApp = new Vue({
  el: '#app',
  data: {
    onEdit: false,
    msg: 'Something in here',
  },
  methods: {
    switchAndFocus() {
      if(!this.onEdit) {
       this.onEdit = true;
       this.$refs.afterClick.focus();
      }
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <span class="before-click" @click="switchAndFocus()" v-show="!onEdit">{{msg}}</span>
  <input type="text" class="after-click" ref="afterClick" :value="msg" v-show="onEdit">
</div>

Answer №1

To ensure the focus event is triggered at the right time, wrap it in a nextTick function - this will delay the focus event until after the DOM update has taken place.

https://v2.vuejs.org/v2/api/#Vue-nextTick

var myApp = new Vue({
  el: '#app',
  data: {
    onEdit: false,
    msg: 'Something in here',
  },
  methods: {
    switchAndFocus() {
      if(!this.onEdit) {
       this.onEdit = true;
       this.$nextTick(function(){
        this.$refs.afterClick.focus();
       });
      }
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <span class="before-click" @click="switchAndFocus()" v-show="!onEdit">{{msg}}</span>
  <input type="text" class="after-click" ref="afterClick" :value="msg" v-show="onEdit">
</div>

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

What is the process for implementing a fallback image in Material UI?

Hey there! I'm currently looking to customize the fallback image of a Material UI Avatar with my own original image. Does anyone have any tips on how I can achieve this? const fallbackImage = "../../fallback/img.png" const AvatarWithBadge = ...

Sorting the Czech alphabet with the help of Tablesorter

Utilizing the tablesorter characterEquivalents extension as outlined in this documentation. I have created a similar extension for Czech characters, but the sorting is not functioning correctly for certain characters - like \u017d $.extend( $.tables ...

Easily resolving conflicts by removing `package-lock.json`

Whenever I work in a team environment, I often encounter merge conflicts with the package-lock.json file. My usual solution is to simply delete the file and generate it again using npm install. So far, I haven't noticed any negative effects from this ...

Is there a similar alternative to ignoring in webpack or browserify?

My code works perfectly in the browser after ignoring two packages with browserify: browserify files.js -i fs-extra -i request --standalone files > files.browserify.js. However, when I try to use webpack instead, the code throws errors about missing mod ...

Creating a reactive "virtual" getter for a class in VueJS

There are two objects in my code, BlogPost and Comment, with the following structure: class Comment { constructor (blogId, text) { this.blogId = id this.text = text } } class BlogPost { constructor (id, text) { this.id = id this.te ...

Error: Issue with hook function call detected. Struggling to locate exact source in React JS

As I dive into React for the first time, I'm working on creating a sign-up form with multiple steps. Despite reading through the material-ui documentation and learning about ReactJS, I'm struggling to pinpoint where I've gone wrong. Here&ap ...

What is the best way to split two sets of radio buttons with the same name into distinct blocks in an HTML form?

For my project, I am working with two sets of radio buttons where the values are stored in a Database. Depending on another result in the HTML form, I need to display one set of radio buttons or the other. The issue arises when using the same name for all ...

How I am able to access this.state in React without the need for binding or arrow functions

Understanding the concept of arrow functions inheriting the parent context is crucial in React development. Consider this React component example: import React, { Component } from 'react'; import { View, Text } from 'react-native'; i ...

Closure-compiler and its peculiar pre-codeyntax

When it comes to minimizing my JS code, I typically rely on the online closure compiler available at . Recently, I've been attempting to incorporate this process into PhpStorm using "External tools," but I seem to be encountering a strange issue. Ever ...

Controlling the angular bootstrap modal form with ease

I am having trouble accessing the form in the modal controller (Plunkr). The variable myForm doesn't seem to be accessible. How can I make the alert call work correctly: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCt ...

Navigating Wordpress posts with a Month data format filter in Vue.js

Can anyone suggest the most effective method for filtering WordPress Posts by month using Vue.js? I am currently retrieving my data from WP_JSON posts, but I need a dropdown menu that allows users to select a specific month such as "September" so that onl ...

A one-page digital space that functions as a dynamic slide show

Check out this cool website I want to emulate. The site is a single-page design where you can navigate vertically using various methods like keyboard, mouse, scroll, or swipe gestures. There are carousels that allow left and right navigation. Each section ...

Deactivating Touchable Opacity Sounds in React Native

Currently, I am in the process of developing an application, utilizing TouchableOpacity instead of a button. I am looking to disable the auditory feedback that occurs when the TouchableOpacity component is pressed. <TouchableOpacity activeOpacity={1} to ...

Pass along computed style data to the parent component in Vue.js

I am relatively new to VueJS and currently in the process of exploring its features. One specific issue I am facing on my website involves a TopBar component that includes both the logo and the menu. <template> <div id="topBar"> <div ...

axios encountering a 400 bad request error during the get request

I've hit a roadblock for some time now while trying to make a call to my API to fetch data using the GET method. I keep getting a 400 bad request error in Postman, even though I am able to successfully retrieve the data with a status code of 200. I ha ...

What is the best way to transfer React context between _document.js and pages in Next.js?

Imagine I have this scenario: export const ThemeContext = createContext(); export function ThemeWrapper({ children }) { const sharedState = { darkMode: false, }; return ( <ThemeContext.Provider value={sharedState}> {children} ...

Create a small circle in the bottom left corner with a constrained size

I'm trying to create a circle at the top of the screen on mobile, similar to the image below. The circle should take up a percentage of space, with the rest of the content appearing against a blue background as shown in the image. However, I'm h ...

Ensure that the Jquery inview element functions both upon initial load and as the user scrolls

I've been working on implementing the inview function by adding and removing a class to an element, but for some reason it's not functioning as expected. Can anyone offer some assistance with this? http://jsfiddle.net/zefjh/ $.fn.isOnScreen = f ...

Deleting the HTML element

Can someone assist me with my script issue? I am facing a problem: when I open my file on fullscreen (over 768px), and move my pointer around the logo div, nothing happens. However, if I resize my browser to below 768px, then back again above 768px, the ...

Do Not Replace Bootstrap Theming

Good day, I am encountering an issue that has left me puzzled. I am attempting to modify the color scheme of bootstrap using SCSS in my Vue project, but it seems to be ineffective when I execute npm run serve. Below are snippets from my files: custom_boo ...