How can I target an input field that is currently visible in Vue.js?

I'm struggling with what should be a basic concept.

Within my <template>, I have the following code:

<div v-if="this.editable">
    <input type="text" ref="nota" :id="notaid" v-model="nombre" v-on:keyup.enter="enviar" v-on:blur="enviar" class="form-control">
</div>
<div v-else>
    <p @click="makeEditable">{{ nombre }}</p>
</div>

Initially, when the page loads, editable=false so it displays text. Upon clicking the text, a function sets editable to true, making the input display. This functionality works fine. However, I'm facing an issue - how can I automatically focus on the input once editable changes to true?

I've searched through some resources like here, here, and others that suggest focusing on the element with a simple line of code:

this.$refs.nota.focus()

The code for the makeEditable method is as follows:

methods: {
  makeEditable() {
    this.editable = true;
    this.$refs.nota.focus()
  },
  ...

Unfortunately, I encounter the following error:

app.js:38487 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'focus' of undefined"

I suspect this is because I'm trying to focus on an element that hasn't been created yet, as targeting an input element that is always visible works perfectly fine.

What would be the correct approach in this scenario?

Answer №1

For implementing asynchronous behavior in Vue, you can utilize Vue.nextTick(callback) method like this:

methods: {
  makeEditable() {
    this.editable = true;
    Vue.nextTick(() => 
      this.$refs.nota.focus()
    )
  },
  ...

This function instructs Vue to wait for changes to take place before executing the callback function.
Refer to the official documentation for detailed information.

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 best way to eliminate the appended content within the tbody?

The code snippet below is functioning correctly. I am trying to retrieve the ID or Class of the appended data from the checkbox. However, when I use the following code $('.chk').click(function(){ console.log(cc);}), it does not work as expected. ...

Errors during the compilation of Webgl shaders in the Google Chrome browser

Currently, I am in the process of learning three.js by following this tutorial: . Despite the tutorial working well, I have encountered errors in my own code which seem like this: ERROR: 0:26: 'nuniform' : syntax error Three.js:325 precision hi ...

When moving through routes in a vuejs single-page application that utilize the same component, the data within the component does not

In my vuejs SPA, I have set up a couple of routes using vue-router: /create/feedback /edit/feedback/66a0660662674061b84e8ea2fface0e4 Both routes use the same component, a form that adjusts its values based on the presence of an ID in the route (feedbac ...

What is the best method for converting the format of an array from a Laravel Controller to Javascript?

How can I convert the format of an array from a Laravel Controller to JavaScript? $data = DB::table('courses') ->selectRaw('courses.course_code,COUNT(student_applicants.status) as total') ->leftJoin('student_ ...

Having trouble compiling your React app after adding 'node-sass'? Here's how to resolve the "Module not found" error

After successfully building a react.js app, I encountered an issue upon installing 'node-sass' using npm install. While the app works seamlessly in the production build, it fails to compile in the development build when using npm start. Surprisi ...

What is the purpose of using the '@attributes' in the code while converting XML to JSON?

I have come across various iterations of the xml2json code that utilize the '@attributes' method, but I am wondering why not simply use obj[attribute.nodeName] = attribute.nodeValue instead? // Converting XML to JSON function xmlToJson(xml) { ...

Setting the Active class for a Pagination element in NextJS using router: A step-by-step guide

I have created a pagination feature that returns an array of values: const pageNumbers = [1, 2, 3, 4, 5, 6, 7, 8] Here is how I styled it: pageNumbers.map((pageNumber, index) => ( <li key={index} className={`page-item number-item ${ ...

Is there a way to trigger the animation of this text effect only when the mouse is scrolled to that specific section?

Here is a cool typing text effect created using HTML, CSS, and JavaScript. Check out the code below: (function($) { var s, spanizeLetters = { settings: { letters: $('.js-spanize'), }, init: function() { ...

What is the method for retrieving the second data variable from a $.ajax() request in JavaScript?

I'm having an issue with my ajax function. I am trying to console.log the first data variable, but the code below isn't working: $('.comment_form').on('submit', function(e) { e.preventDefault(); $.ajax({ type: ...

Assign the serialized form data retrieved via Ajax to a JSON object

Below is the HTML form I have created: <form role="form" id="booking" class="form-horizontal" action="booking.json" method="POST"> <div class="form-group"> <label for="destination">Destination:</lab ...

JavaScript code to fetch data from a MySQL database

I am looking to dynamically retrieve data from a MySQL database using PHP in JavaScript variable. The current data is static and I want to make it dynamic by fetching it from the MySQL database without altering the format. Specifically, I need to extract ...

Placing a cookie using nookies within the Next.js API directory

I'm currently facing an issue while trying to use the nookies npm package to set a cookie within the Next.js api folder. I've successfully set up a cookie using the same code with nookies before, but for some reason, it's not working in this ...

Once the object was placed in the array, it no longer exhibits reactivity

Why did the element's reactive property turn into a non-reactive one after passing through the reactive array? Can you please explain this phenomenon? <script setup lang="ts"> import { ref, Ref } from 'vue' inter ...

Conceal Navigation with jQuery

Seeking assistance with jQuery for a new project. I'm trying to create a navigation menu that will automatically disappear after 3 seconds when a user enters the page. In its place, an arrow will be displayed instead of the original menu. Once the a ...

Vue.js doesn't bind the href link to the button correctly

Is it possible to bind the href attribute to a button in VueJS 2.5? While it works fine for traditional hyperlinks, I am wondering if there is a way to achieve this specifically for buttons within the Vue framework. <script src="https://cdnjs.cloudfl ...

Troubleshooting Issues with AngularJS HTTP.get Requests

I'm currently working on a simple AngularJS application that is supposed to extract data from a .json file. While my code doesn't show any errors upon running it, it fails to retrieve the JSON values as expected. I have a feeling that I may be ov ...

Switching fields between different objects in MongoDB and Node.js

Currently, I'm in the process of developing a Javascript application that enables users to rearrange elements within a MongoDB database. Each entry in the database contains a "order" field which signifies its position. When a user chooses to move an ...

Unable to connect state to props when utilizing combineReducers

I'm currently working on integrating my state with a specific component using Redux. To achieve this, I have implemented two reducers and utilized combineReducers to merge them into a rootReducer before initializing my store. const rootReducer = comb ...

AngularJS not refreshing the view

I'm having an issue in my app where I calculate the total bill and display it on my view. The first time, everything works fine. However, when I increment the $scope.bill_total, the view is not updating even though I can see the change in the console. ...

When the checkbox is clicked, use onclick to establish a PHP session to remember the checkbox state. If the

Here is the form I have created: <input type="checkbox" name="dept" value="sales" <?php if(isset($_POST['sales'])) echo "checked='checked'"; ?> onclick="this.form.submit();" /><br /> After clicking the checkbox, the ...