How to toggle classes on specific items generated with Vue JS's v-for directive

I have a list rendering using the v-for directive in Vue.js.

<li v-for="group in groupList" :key="group.id" @dragenter="toggleClass ...."@dragleave="toggleClass ...." >

      Content

       </li>
   

My goal is to apply a class to the li element when the dragenter event occurs. How can I achieve this? How do I access the element itself (not just its data) inside the event handler, and how can I toggle the class based on that reference?

While I understand that Vue promotes data-driven changes to reflect on the DOM, I am looking for a more concise solution that doesn't rely on indexes or IDs within the data model. Thank you.

Answer №1

To access the li element that is being dragged in the dragenter callback, you can use event.currentTarget (or event.target would also work in this scenario). Here, event refers to the parameter of the callback function.

new Vue({
  el: '#app',
  data() {
    return {
      grouplist: [
        { id: 1, text: 'a' },
        { id: 2, text: 'b' },
        { id: 3, text: 'c' },
      ]
    }
  },
  methods: {
    onDragEnter(e) {
      e.currentTarget.classList.add('drag-enter');
    },
    onDragLeave(e) {
      e.currentTarget.classList.remove('drag-enter');
    }
  }
})
.drag-enter {
  background: #eee;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4630332306746873687770">[email protected]</a>"></script>

<div id="app">
  <p draggable>Drag this text over the list items below</p>
  <ul>
    <li v-for="group in grouplist"
        :key="group.id"
        @dragenter="onDragEnter"
        @dragleave="onDragLeave">{{group.text}}</li>
  </ul>
</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

The attempt to execute 'removeChild' on 'Node' was unsuccessful because parameter 1 is not the correct type. Although it did remove the elements from the DOM, it only did so once

It's quite a challenge I'm facing!!! Although there have been similar questions asked before, they were all for specific scenarios. I am currently developing a tictactoe game using the module design pattern. The function below helps me create tw ...

Merging the `on('click')` event with `$(this)`

Hello everyone, this is my first time posting here. I have a question regarding the possibility of achieving a specific functionality. I would like to attach click events to a series of anchor links and then use the $.get() method to reload some icons. T ...

What is the best way to access the current value and name of a textbox in real-time using

How can I retrieve the value of a textbox in JavaScript using onblur and on keyup events, while also performing real-time checking for each individual textbox using "this keyword"? Here is my JSFiddle link. Can you assist me in modifying it? ...

Can you explain how the Facebook Like button code functions and how I can create a similar feature on my own platform?

I have a website with 250 different items, each containing its own Like button using the standard Facebook "Like" code: div class="fb-like" data-href="http://www.mywebpage.com/myproductpage" data-send="false" data-layout="button_count" data-width="80" dat ...

Can you explain the distinction between 'ssr:false' and 'target:static' in NuxtJS?

When creating a static site with NuxtJS, it appears that there are 2 choices to make: setting either ssr:false or target:static in the NuxtJS configuration file (nuxt.config.js). Do these options essentially accomplish the same thing? Why are both availa ...

Utilizing JQuery for parsing information

I am working on a project that involves displaying Google Maps API on one tab and images on another within a container. The goal is to have the image in the second tab change when a location is selected from the list. To achieve this, I have set up a hidd ...

Vue's push() method is replacing existing data in the array

I'm currently facing an issue where I am transferring data from a child component, Form, to its parent component, App. The data transfer is functioning correctly, however, when attempting to add this data to the existing array within the App component ...

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

Error: Unable to access 'push' property of null object in Next.js Link

Utilizing Vite to develop a reusable component has led to an error upon publishing and reusing it: TypeError: Cannot read properties of null (reading 'push') The code for the component is as follows: import React from "react"; import ...

Experiencing the "Module not found" issue while incorporating SCSS into React applications

I attempted to apply a SCSS style to my "Logo.js" component, but I am still unable to resolve the error that keeps popping up: ERROR in ./src/components/Logo/Logo.js 5:0-19 Module not found: Error: Can't locate 'logo.scss' in '/Users/a ...

Creating form elements in ReactJS dynamically and storing their values in an array

I need to render 3 materialUI TextFields multiple times, depending on the integer input by the user before rendering the form fields (the integer is stored in a variable called groupMembersCount). I am using a functional component in ReactJS with an array ...

What is the best way to save the toggleClass value of various selectors along with their corresponding classes in localStorage?

I've been attempting to preserve the toggled class of multiple elements using local storage or cookies in order to maintain the toggled class after a page refresh. Despite trying various solutions such as js cookie and other tutorials, I've had n ...

How to properly import components and CSS in Vue.js for optimized performance

As a beginner in vue.js, I find one particular concept to be quite confusing. Can someone help clarify the difference between importing a vue.js "component" and a CSS file? For example, when considering bootstrap and vue-bootstrap, do I need both? Just o ...

Component does not detect change when the same number is sent as input

Let me paint you a picture: I have this nifty component, set up with the OnPush strategy, that showcases a PDF document, sliding through pages one by one, and granting users the ability to smoothly glide through pages and jump to specific ones. It even of ...

The Vuetify tooltip appears to be invisible in the HTML document

After implementing the example from the documentation into my component's template: <v-tooltip bottom> <template v-slot:activator="{ on }"> <v-btn color="primary" dark v-on="on">Button</v-btn> </template> <s ...

gmap3 has encountered an error: undefined is not a valid function

I am working on a WordPress site and trying to integrate a Google map into the contact page. However, I'm encountering an error Uncaught TypeError: undefined is not a function in the JavaScript console. Below is the code snippet causing the issue, can ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

Instructions for inserting an anchor tag into the middle of a <p> element utilizing document.createElement("p")

When generating elements dynamically with JavaScript using document.createElement("p"), I am looking to create a paragraph element <p></p> that includes an anchor tag in the middle, creating a clickable link within the text. I aim to use JavaS ...

Glitchy/Crazy CSS3 Animations

Currently, I am developing a website at . One of the features I have implemented is CSS3 transitions for route changes, but this feature only works in Chrome. Here's how the animation works: I apply the .preanimate class to rotate the phasing out di ...

Sharing data between two components on the same level in Vue.js

I have a situation where I need to transfer data from one component1 to another component2. I am not utilizing vuex or router for this task. The component tree looks like this: -Parent --Component1 --Component2 In the first component1, I am sending an ...