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

Leveraging the querySelector() method within the Vue Composition API

I'm currently exploring the Vue Composition API and am running into issues with using document.querySelector. When I attempt to use it like this: <nav class="home-menu pure-menu pure-menu-horizontal pure-menu-fixed"> <script setup& ...

Experiencing difficulty with passing a jQuery array to PHP

I am trying to pass the values of an array from a JavaScript variable to PHP using AJAX. The issue I'm facing is that after clicking the send button and checking the PHP file to see if the values were passed, it appears empty. However, when I inspec ...

JavaScript conflicts will arise due to the introduction of Yammer Embed on September 30th, 2014

Is anyone else encountering problems with Yammer embed causing JavaScript errors today? Our various applications across different technologies (SharePoint, IBM, etc) have been functioning normally for months, but this morning we are suddenly seeing a sig ...

Enhancing Redux efficiency with substantial data structures

I have developed a web application using Redux and React. It is an analytics application that displays a significant amount of data. However, I am facing performance issues as the size of my data store increases. What is the best approach to prevent perfo ...

Steps for resetting the Vue 3 scaffolding

Two options to scaffold a new Vue project are npm init vue@latest and npm create vue@3. I recall there is a specific command that allows you to re-initialize the scaffolding process in order to add additional features like TypeScript or Cypress. Unfortuna ...

Having trouble getting ng-click to function properly in TypeScript

I've been struggling to execute a function within a click function on my HTML page. I have added all the TypeScript definition files from NuGet, but something seems to be going wrong as my Click Function is not functioning properly. Strangely, there a ...

Exploring the Power of Angular Toastr Callback Functions

Hey there! I'm currently working with Angular Toastr to display messages on my screen. I have a setup where only two messages can be open at the same time - one for errors and another for warnings. These messages are persistent and require user intera ...

Leveraging ThemeProvider Parameters with Global Styled-Components

When working with styled-components, how can I access the props of the ThemeProvider in the context of global.js? For instance, in my theme.js file, I have ${props => props.theme.fonts.fontSize} set to a default font size of 16px. const theme = { ...

External API data is shown in the browser console but appears as undefined on the page

Can you please lend me a helping hand? I am facing a critical issue while attempting to retrieve data from an external API using axios in NextJS (Reactjs)/TypeScript through getServerSideProps. The data fetching is successful, and the JSON is returned on t ...

Acquiring mapping information through JSON data retrieval

Overview : Each levelNum has three corresponding dropdowns. For example, the dropdown for levelNum2 includes (Department-Unit-1, Department-Unit-2 & Department-Unit-3), levelNum3 includes (Division-Unit-1 & Division-Unit-2), and levelNum4 includes ...

Exploring the World of Angular JS Services

Following the recommended practices, I am working on encapsulating my global functions into reusable factory services. In the provided code snippet, my objective is to execute a function that takes the string value of "Qprogress" from my JSON data, perform ...

Is it possible to restart an animated value in React Native?

I'm facing an issue in my react native app where I have created a simple animated progress bar, but I am unsure how to reset the animation. I attempted the following approach without success: progressValue = 0; How can I reset the animation? Also, w ...

The carousel is failing to display two items on each slide

I've integrated a carousel library from npm into my project. However, I'm facing an issue where I need to display two cards in each slide within the carousel. Here's a snippet of my code: Catalog.js import React from 'react'; impo ...

Retrieve specific JSON information

Below is an example of JSON data: [{ "RM_Name": "Russ Martin", "Division": "East", "RM_Phone": "(603) 491-1259", "RC_Name": "Jacob Sucoff", "RC_Phone": "(800) 247-4154 x3403", "States_Covered": "MT,VT, NH, ME (all firms)", "La ...

Is there a way to utilize a parameter for the user's input instead of relying on document.getElementById when incorporating a button?

let totalScore = 0; var myArray = [1, 2, 3, 4, 5]; let randomNum; function NumGuess(userInput) { var userGuess = userInput; var i; for (i = 0; i < 1; i++) { var randomNum = myArray[Math.floor(Math.random() * myArray.length)]; } if (us ...

The AJAX Request has indicated that the entity provided is not in an accurate 'application/json' format. It seems to be missing or empty, leading to an error with a code of '400'

While attempting to create an AJAX request to submit users to an external API, I faced a problem that is hindering my progress. Since I'm more familiar with PHP than JS, I saw this as an opportunity to expand my knowledge in JavaScript. The approach ...

Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly. Here is a snippet from my app.js: import { createApp } from "vue" const app = createApp({}) // pinetree i ...

Display of undefined data in Ajax success response

After receiving an array object data in the Ajax success result, I am trying to print li tags but they are showing as undefined. This is my Ajax code: $.ajax({ 'method': 'GET', 'url': base_url +'party/sel ...

Storing a JSON response in a variable

I need assistance with using the Google Geocoder API to obtain the longitude and latitude of an address for a mapping application. How can I retrieve data from a geocode request, like this example: "http://maps.googleapis.com/maps/api/geocode/json?address ...

Setting up Zurb Foundation in a VueJS TypeScript project: Step-by-step guide

I'm currently facing a challenge involving the integration of Zurb Foundation v6.5.3 into a VueJS project that is TypeScript-based and was created using @Vue/CLI. The project already includes jQuery type definitions. In the code snippet below, you can ...