It appears that Vue.js's this.$nextTick() function does not properly wait for the DOM to finish rendering

Having trouble with nextTick() in Vue.

Here's the template code: In the template:

<template>
  <div>
    <div v-if="editing">
      <span ref="theInput"
            contenteditable="true">{{ someValue }}</span>
    </div>
    <div v-else>
      <span>{{ someValue }}</span>
    </div>
    ...
</template>

And the script code:

data() {
  editing: false
}
...
methods: {
  toggle() {
    this.editing = ! this.editing;
    if (this.editing) {
      this.$refs.theInput.focus();
    }
  }
}

When trying to focus on this.$refs.theInput, it's not rendered yet.

My current workaround involves adding a timeout, but I know it's not the best solution:

methods: {
  toggle() {
    this.editing = ! this.editing;
    if (this.editing) {
      setTimeout(() => this.$refs.theInput.focus(), 100)
    }
  }
}

I also attempted a cleaner approach using this.$nextTick(), but encountered the same issue:

methods: {
  toggle() {
    this.editing = ! this.editing;
    if (this.editing) {
      this.$nextTick(() => {
        this.$refs.theInput.focus();
      });
    }
  }
}

Shouldn't nextTick() wait for the DOM to render before focusing on theInput? Appreciate any help you can provide.

Answer №1

Discovered the solution by repositioning $nextTick in a more appropriate location. The corrected code looks like this:

methods: {
  toggle() {
    this.editing = ! this.editing;
    this.$nextTick(() => {
      if (this.editing) {
        this.$refs.theInput.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

How to deactivate the mobile hardware back button functionality in Ionic 2

Our team has been developing a business application and we've encountered a perplexing issue. Every time we press the mobile hardware back button, our application's GUI becomes disrupted. Despite dedicating numerous hours to finding a solution, t ...

Organizing data in a bar chart with D3.js through the d3.nest() function

I am new to d3.js and my JavaScript skills are at a basic level. Thank you for your assistance, it is greatly appreciated. Total Clicks per Campaign I have a CSV file with columns: "Campaign" and "Clicked". The "Clicked" column contains values: Clicked ...

Playing around with jQuery to manipulate tables

Is there a way to exclude the first td from triggering a click event in jQuery? I want to prevent the dialog box from appearing when clicking on the first td of each row. jQuery("#list tbody tr").not(':first-child').click(function(){ //some cod ...

What is the best way to transform the request query id = ' [12eetftt76237,jhgasduyas7657] ' into an array of elements or strings like [12eetftt76237,jhgasduyas7657]?

Hey there, I am working on a project using hapijs and typescript. I have a requirement to send an array of IDs as parameters through the request URL. Here is an example of the URL: localhost:3444/?id='[askjajk78686,ajshd67868]' I attempted to u ...

Adjust the minimum height and width when resizing the window

Apologies in advance if this has already been addressed, but I have tried solutions from other sources without success. My Objective: I aim to set the minimum height and width of a div based on the current dimensions of the document. This should trigger ...

Can you merge multiple req.body requests?

I am exploring a scenario where I have a list of items that need to be iterated through, with each item having the value of i added to it to retrieve the next set of information. For example: By concatenating the string "req.body.item" + i + "Title", you ...

Passing Props in Vue-Router: A Guide

I've encountered an issue with passing props using Vue-Router. I'm struggling to access the props in the next view after routing. Here is my methods object: methods: { submitForm() { let self = this; axios({ method: &apo ...

Steps to integrate the Save as PNG functionality in Vega using a customized menu

As I develop a data dashboard with Vega for visualizing outputs, I decided to customize the menu system by removing the actions dropdown. However, I still want to incorporate the "Save as PNG" option from the original dropdown (as shown in the image below) ...

Using Vanilla JavaScript library in Angular 6 - A Comprehensive Guide

I encountered an error while trying to import a Vanilla JavaScript library into an Angular 6 component. Can you please provide me with some guidance on how to resolve this issue? This is the syntax I used to import the library: import * as ExistingLibrar ...

Clicking the delete button in Firebase to remove an item

I am in the process of developing a simple CRUD application and have opted for Firebase as my backend solution. While I have successfully implemented the create and read functionalities, I've hit a roadblock with the delete operation. When attempti ...

Unable to utilize the .keyCode method within a query selector

Trying to utilize .keyCode in JavaScript to identify a pressed key, but the console consistently displays null after each key press. Below is the relevant CSS code: <audio data-key="65" src="sounds\crash.mp3"></audio> ...

Utilizing nested HTML within an HTML tag

Recently, I've been exploring the concept of nested HTML in Bootstrap. While following a tutorial on using Popovers, I encountered the following code; <button id="btn3" type="button" class="btn btn-primary show" ...

Problem with Resetting State in Cordova/AngularJS

Currently, I am facing a challenge with my Cordova/AngularJS mobile application as I struggle to refresh the current state with new data. Please be aware that this is not an Ionic Framework application. The issue arises in the part of my app where I need ...

Exploring the differences between arrays and filter functions within MongoDB aggregation operations

Recently, I crafted a sophisticated pipeline for my database: let orders = await Order.aggregate( { $unwind: "$candidate", }, { $lookup: { from: "groups", localField: & ...

.htaccess file is causing js and css files to not load

I followed an MVC tutorial by howcode on YouTube, but I encountered an issue where my CSS and JS files were not loading due to the htaccess configuration. .htaccess file: RewriteEngine On RewriteRule ^([^/]+)/? index.php?url=$1 [L,QSA] I attempted vario ...

Run a PHP script on the current page upon choosing an option from a dropdown list with the help of Ajax or JavaScript

I'm currently working on a MySQL query that needs to be executed when a user selects options from multiple dropdown lists. What I am looking for is the ability to automatically run a query related to the selected dropdown list option using AJAX/JavaS ...

The fading effects are not functioning as expected in the following code

Hey there, I'm not the most tech-savvy person, but I managed to come up with this code for page redirection. Unfortunately, I couldn't quite get the fade out and fade in effects to work properly when executing it. If anyone out there can help me ...

Using the power of jQuery to load Ajax content, unfortunately, the content remains

Hey there, I'm currently working with an HTML file that utilizes AJAX to load content from other HTML files on the same server. However, for some reason, it's not functioning properly. I'm new to AJAX and I'm not sure what could be caus ...

Submitting both $_POST[] data and $_FILES[] in a single AJAX request

Struggling with uploading images along with dates on my website. I am passing the date using $_POST and the image files in $_FILES. Here is the Javascript code snippet: (function post_image_content() { var input = document.getElementById("images"), ...

Why is req.app.post(...)create_event not functioning as expected?

Currently, I'm utilizing axios, node.js, express.js, and SQL to send a post request to my database. However, each time I attempt to do so, I encounter an error message stating: "TypeError: req.app.post(...).create_event is not a function". I've b ...