Implementing dynamic class bindings with Vue.js using v-for

I am currently using a v-for loop in Vue.js to create a list of items populated with data from an API. Here is an example of the items array:

items: [
   {
       foo: 'something',
       number: 60
   },
   {
       foo: 'anything',
       number: 15
   },
   {
       foo: 'text',
       number: 20,
   }
]

Template

<div v-for="(item,index) in items" :key="index">
     <div :class="{ active: ????}" @click="toggleActive">
          {{ item.foo }} 
          {{ item.number }}
     </div>
</div>

JS

methods: {
    toggleActive() {
        //
    }
}

I am looking for a solution where clicking on a div will add the class "active", and if it already has the class then it should be removed (toggled). Additionally, multiple items should be able to be selected.

Is there a way to achieve this without adding a boolean variable to the items array or moving each item into a separate component?

Answer №1

Here is the solution for you.

new Vue({
  el: "#app",
  data: {
    items: [{
        foo: 'something',
        number: 60
      },
      {
        foo: 'anything',
        number: 15
      },
      {
        foo: 'text',
        number: 20,
      }
    ]
  },
  methods: {
    toggleActive(index) {
      let item = this.items[index];

      item.active = !item.active;

      this.$set(this.items, index, item);

    }
  }
})
.active {
  color: red;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0274776742302c372c3335">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <div v-for="(item,index) in items" :key="index">
    <div :class="{ active: item.active}" @click="toggleActive(index)">
      {{ item.foo }} {{ item.number }}
    </div>
  </div>
</div>

Explore the working code on JS Fiddle: https://jsfiddle.net/eywraw8t/250008/

Answer №2

MainComponent.vue

<template>
     <div>
        <div 
        v-for="(item, index ) in items" 
        :key="index"
        :class="{ active: index === activeIndex}"
        >
         // Displaying looped items from data
         // Button to toggle item activation
            <button @click="activateItem(index)"> Make this item active </button>
        </div>
    </div>
</template>
 

Data and Methods

<script>
export default {
    data() {
        return {
            activeIndex: null,
        };
    },
    methods: {
        activateItem(index) {
            this.activeIndex = index;
        },
    },
};
</script>

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

If you try to wrap an object with an anonymous function, you'll receive an error message

Consider the following straightforward example. (function() { var message = { display: function() { alert('hello'); } }; })(); When trying to implement message.display(); An error is triggered stating ReferenceError: message ...

In JavaScript, when a div element contains an iframe, the click event will not trigger on the div

Check out this sample HTML markup: <div> <iframe></iframe> </div> The iframe is set to fill the outer div. I've added an event handler to the div click event: div.addEventListener("click", function () { console.log( ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

Using the code `$("img").one('load'` can trigger only a single load event without repetition

I have implemented the following function: function CheckImage(url, index) { $("<img/>").one('load', function () { $("div.photos").append(this); }).attr('src', url).attr('data-photo', '0' + ind ...

Display information from dynamically generated pages using Gatsby JS sourcing data from CSV files

I've been working on creating pages in Gatsby JS from a csv file and everything seemed to be going smoothly. However, when it comes to displaying the data on these generated pages, I keep running into issues with undefined variables and can't see ...

What is the best way to update parent data from a child component?

Upon further investigation, it appears that updating data from child to parent should be done by emitting events rather than using v-model. Here is my attempt at implementing this method (unsuccessfully). App.vue <template> <div> <Hel ...

Creating point illustrations with Three.js

Looking to incorporate random points into a web project using Three.js. Here's the current code: <script type="module"> import * as THREE from 'https://threejs.org/build/three.module.js'; import { TrackballControls ...

Using multiple conditions in an angular ngif statement to create a variable

Is it possible to assign the result of a function to a variable in Angular (13) within the .html section of a component, specifically with multiple conditions in ngIf? <div *ngIf="let getMyVar() as myVar && isVisible && isClean" ...

Is there a way to resolve the issue of Vue's v-html not supporting promises, etc.? It seems that all Vue binding values do not support promises

my project's code involves the formatter method, which might incorporate async functions and the use of async and await. However, when I implement them, the page does not render properly. Is there a solution to this issue? ...

Tips for accessing the @keyframes selector and extracting the value from it

In my CSS code, I have a shape element with an animation that spins infinitely for 50 seconds. #shape { -webkit-animation: spin 50s infinite linear; } @-webkit-keyframes spin { 0% { transform: rotateY(0); } 100% { transform: rotateY(-360deg ...

Using an Angular route to trigger the resolution of data from a service

I'm having trouble figuring out how to implement Angular route resolve. The documentation does not provide much help for more complex aspects of the javascript framework like this. Here is the service I am using: app.service("AuthService", ["$http", ...

What is the method for providing a date format choice in JSON?

I am encountering an issue in my PHP script where I use JSON to pass parameters. When I pass the date as "09-09-2015", it functions correctly. However, when I try to pass the date as $date, it does not work. How can I resolve this problem? $item1 = "test ...

Utilizing One-to-Many Microphone Streaming Technology

I'm looking to create a unique one-to-many microphone streaming system where a user can record from their microphone and others can listen in. I also need to be able to record the microphone session. Would it be better to use WebRTC for client commun ...

Using Typescript to typecast in D3.js

Utilizing the D3 graph example available here. I've defined my data object as shown below: interface ID3Data { age: string, population: number } const data: ID3Data[] = [ { age: "<5", population: 2704659 }, { age: "5-13", population: 4499 ...

JavaScript TweenJS is a powerful library that simplifies

Hey there, it's my first time posting on Stackoverflow. I'm facing an issue with a tween in my code. It seems like the brute function is being called at the end, indicating that the tween should be running. However, I'm not seeing any actual ...

Navigating through a mergeMap observable with an undefined value

In my Angular 6 app, I have a class that attaches API tokens to every http request using the getIdToken() method. If the token retrieval is successful, everything works fine. However, if it fails, my app will stop functioning. I need help with handling th ...

What is the best way to show a macOS progress pie loading icon alongside files?

While using macOS, a pie loading icon appears next to a file during downloading or transferring. To illustrate, here is an example of a file being downloaded from Chrome: I am interested in implementing a similar feature in my Electron/Node application. ...

adding numerous items to an array using JavaScript

How can I add multiple objects to an array all at once? router.post(`/products`, upload.array("photos" , 10), async (req, res) => { console.log(res); try { let product = new Product(); req.files.forEach(file => { product.p ...

The function for utilizing useState with a callback is throwing an error stating "Type does not have

Currently, I am implementing the use of useState with a callback function: interface Props { label: string; key: string; } const [state, setState] = useState<Props[]>([]); setState((prev: Props[]) => [...pr ...

Utilize the ESLint plugin to manage unresolved import paths in Next.js modules

Utilizing module import from next and attempting to import a component as shown below: import Navbar from '@/components/Navbar/Navbar'; Upon running npm run lint, an error is returned stating: 1:20 Error: Unable to resolve path to module &apo ...