Interact with an item by selecting from a list generated by Vue's v-for directive

Whenever I click on a specific element in the v-for loop, I want to receive feedback within that same element. However, I am running into an issue where the feedback is only displayed after the second click on the element.

This Vue code snippet

<i @click="addToCart(dish), getFeedback(dish);" class="fa-solid fa-plus d-flex justify-content-center align-items-center mt-3"></i>
<span class="alert alert-primary d-none">
You have added the dish to the cart
</span>
This is the method


getFeedback(){

          const addDish = document.querySelectorAll('.fa-plus');
          const alert = document.querySelectorAll('.alert');        

          // ISSUE ON SECOND CLICK
          for(let i = 0; i < addDish.length; i++){
            
            addDish[i].addEventListener('click', function(){
                alert[i].classList.remove('d-none');  
                addDish[i].classList.remove('d-flex');
                addDish[i].classList.add('d-none');
                setTimeout(function(){
                  alert[i].classList.add('d-none');
                  addDish[i].classList.add('d-flex');
                  addDish[i].classList.remove('d-none');
              },2000);
              })
          }
        },

Answer №1

When you click for the first time, a for loop is executed and a new event listener is added. It's important to note that this event listener will not run during the same click on which it was added. The initial click has already occurred, and adding the new listener is simply a consequence of that first interaction. Subsequently, when you click again, the event listener that was added by the initial click will trigger, executing your additional code. It appears unnecessary to have this supplementary event listener. To resolve the issue in your code, all you need to do is remove the line addDish[i].addEventListener (along with its closing bracket).

for(let i = 0; i < addDish.length; i++){
                alert[i].classList.remove('d-none');  
                addDish[i].classList.remove('d-flex');
                addDish[i].classList.add('d-none');
                setTimeout(function(){
                  alert[i].classList.add('d-none');
                  addDish[i].classList.add('d-flex');
                  addDish[i].classList.remove('d-none');
              },2000);
          }

However, I must emphasize that this approach is not very Vue-like. In Vue, directly manipulating/querying the DOM should be avoided unless absolutely necessary. If you find yourself doing this frequently, it may indicate that you're not utilizing Vue's capabilities effectively. For instance, in your scenario, implementing a simple boolean flag with conditional rendering using v-if and v-else could replace all your DOM manipulation logic. Check out my demonstration in the following codesandbox for a clearer illustration.

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 property 'rows' cannot be read because it is undefined

While working through the steps outlined in Getting started with Postgres in your React app, specifically when processing and exporting the getMerchants, createMerchant, and deleteMerchant functions, I encountered an error that says: "TypeError: Cannot rea ...

Customize your payment with a PayPal button tailored to your desired price

I've been tasked with creating a dynamic PayPal button that can receive different values based on user choices. The website has so many options that creating separate buttons for each choice doesn't seem feasible. I've tried researching solu ...

Using Node.js to retrieve JSON objects from an API call with node-postgres

After carefully following the instructions on connecting to my postgres table using async/await provided at , I have successfully set up routes to retrieve and display user data. By accessing localhost:3000/users/1, the browser displays the JSON string fo ...

How to extract a value from a span input textbox using Vue?

I just started using Vue and I'm attempting to create an auto-growing input. I've realized that it's not possible to create a real <input> element that adjusts its size based on its content and allows for value modifications using v-mo ...

Is it possible for me to introduce an additional variable to the String.prototype object?

I have a question that has been bugging me out of curiosity. I was thinking about whether I can add an additional variable in front of String.prototype. For instance: $.String.prototype.functionName = function(){}; Obviously, this doesn't work as i ...

Using VeeValidate with v-menu

Has anyone been able to successfully apply veevalidate to vuetify's v-menu component? I've tried using the validation-provider container with other HTML inputs and it works fine, but when I try to integrate it with v-menu, it doesn't seem t ...

What is the best way to ensure that my $.ajax POST call works seamlessly with SSL?

Below is the JavaScript code I am using: parameter = "name=" + name + "&email=" + email + "&phone=" + phone + "&comments=" + comments; $.ajax({ url: 'sendEmail.php?' + parameter, success: ...

How can I add multiple filters to a Kendo Grid?

Is there a way to include two separate filter fields for date filtering in Kendo Grid UI? Currently, the method I am using only allows for one date filter to be displayed. filterable: { ui: function (element: any) { element.ken ...

jqxChart displaying data with proportions

Exploring the waterfall series feature of the jqxChart was quite interesting. As per its API, the code snippet below is used to set the values of the y-axis: valueAxis: { title: {text: 'Population<br>'}, unitInterval: 1000000, ...

What are the steps to integrating a chat feature into my web application using Vue and Java EE?

I have developed a Web Application using Vue.js, REST(JSON), and Java EE with Payara Server as the backend. Now I am looking to integrate a chat feature into my application. The chat should include fixed chat rooms (global, groups) as well as private user ...

Experience seamless navigation with Highstock's fluid panning feature

I'm attempting to achieve seamless panning on a basic highstock chart by clicking and dragging within the plot area. Interestingly, I have found that this works flawlessly when my data is not based on timestamps: data: [-25.1,-23.8,-19.9,-19.1,-19.1 ...

Exploring the process of connecting search values in MongoDB using Mongoose

In the /search/:query route, I have the code snippet shown below: var param = { query: req.query['query'] } MyModel.find({ "$or": [ { 'name': req.param.query }, { 'age': req.param.query } ...

Navigating between divs with a 100% height using up and down movements

I am working on a website that is structured into different sections using divs with shared classes but unique IDs. Each div is set to take up 100% of the viewport height. To navigate between these sections, I want to provide Up/Down arrow buttons for user ...

React onClick event image attribute is unique because it allows for interactive

Is there a way to dynamically add the onClick attribute to an image, but have the click event not working? //Code const parser = new DOMParser(); const doc = parser.parseFromString(htmlContent, "text/html" ); const imageDa ...

How can I pull the account creation date stored in MongoDB and display it using Handlebars?

Currently in my development, I am utilizing MongoDB, NodeJS, and Handlebars. My challenge is to convert the user.id into a timestamp and then display this timestamp on my HTML page. At present, I can display the user.id by using {{ user.id }} in my code, ...

Node.JS, R, and Python are used for intensive computing tasks such as identifying when a callback function has finished executing and

My Node.js REST API exposes endpoints that trigger R and Python scripts for complex computations. Prior to executing these scripts, I must first identify the callback, assign a unique ID to it, and quickly send back the ID to the consumer. The consumer wil ...

Issue with Vuetify's v-checkbox component: selections are not being updated properly

I am faced with a challenge in generating a grid of checkboxes dynamically from a list of judges, each having checkboxes for various tests. While updating the selections for individual judges works well, I encounter issues when I try to modify selections ...

Real-time changes may not be instantly reflected in the model update

I need to add two numbers together and display the sum in a third input field: HTML <div ng-app="myApp"> <div ng-controller="MainCtrl as mainCtrl"> Main {{mainCtrl.foo}} <br/> <input type="text" ng-model="mainCtrl.foo"/> ...

Leveraging Vue multiselect for modifying Algolia database index

In my current setup, I have a functionality on a page that allows me to switch between Algolia indices using the following code: <template> <button @click="selectedIndex = a">List A</button> <button @click ...

Having difficulty executing the command 'npm install -g expo-cli'

When attempting to execute npm install - g expo-cli on a Windows 10 machine, I am encountering issues. An error message keeps popping up and preventing me from proceeding. I'm in desperate need of assistance! npm WARN deprecated <a href="/cdn-cgi/ ...