[Vuejs]-Do something by clicking on an element of a v-for of Vue

0👍

The first click runs the for loop and adds a new event listener. That event listener will not run on the same click you add it! The click has already happened, and adding the new listener is the result of the first click. The second click will then run the event listener added by the first click which then runs your additonal code. There doesn’t seem to be a good reason to have that additional event listener. To fix your code all you should need to do is remove the addDish[i].addEventListener line (and it’s 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 have to state this entire strategy isn’t a very Vue-like solution. There are very few reasons with Vue to directly query/manipulate the DOM. If you’re doing it a lot, it’s probably a sign that you’re not leveraging the power of Vue correctly. For example with your code a simple boolean flag with conditional rendering using v-if and v-else could replace all your DOM code. See my example codesandbox for what I mean.

Leave a comment