Using Vue.js to toggle a class when clicked with the v-for directive

Is there a way to efficiently toggle classes in vue.js for rendered list elements? Building upon the insights shared in this previously addressed question, I am seeking a method to individually toggle each element as well as collectively toggle all of them. Despite my attempts with the code provided below, the solution feels fragile and unresponsive.

Alternatively, is it feasible to utilize a singular variable for toggling all elements while allowing each element to possess its own local variable for individual toggling? Implementation guidance on this approach would be greatly appreciated.

// HTML snippet
<button v-on:click="toggleAll"></button>
<div v-for="(item, i) in dynamicItems" :key=i
     v-bind:class="{ active: showItem }"
     v-on:click="showItem[i] = !showItem[i]">
</div>

// Vue.js application logic
//dynamicItems and showItem will be populated based on API response
data: {
    dynamicItems: [], 
    showItem: boolean[] = [],
    showAll: boolean = false;
},
methods: {
    toggleAll(){
        this.showAll = !this.showAll;
        this.showItem.forEach(item => item = this.showAll);
    }
}

Answer â„–1

Below is a simple example to achieve what you desire. It's not an exact copy of your code, but rather an alternative approach.

var app = new Vue({
el:'#app',
data: {
    dynamicItems: [
      {id:1,name:'John',selected:false},
      {id:2,name:'Doe',selected:false}
    ],
    selectedAll:false,
},
methods: {
    toggleAll(){
      for(let i in this.dynamicItems){
         this.dynamicItems[i].selected = this.selectedAll;
      }
    }
}
});
.active{
  color:red;
  font-size:18px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.9/vue.js"></script>
<div id="app">
<template>
<input type="checkbox" v-model="selectedAll" @change="toggleAll"> Toggle All 
<div v-for="(item, i) in dynamicItems">
  <div :class='{active:item.selected}'><input type="checkbox" v-model="item.selected">Id: {{item.id}}, Name: {{item.name}}</div>
</div>
{{dynamicItems}}
</template>
</div>

Answer â„–2

Simply follow these steps:

v-bind:class="{ active: showItem || showAll }"

After that, delete the final line in the toggleAll section.

It is also important to note that when updating array values, Vue.set must be used due to non-reactive nature of array elements. You can learn more about this at Vue.js documentation.

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

Encountering an obscure issue when using Discord.js v14 after attempting to cancel and resubmit a modal

I'm currently working on a Discord bot using modals in Discord.js v14. These modals appear after the user clicks a button, and an .awaitModalSubmit() collector is triggered to handle one modal submission interaction by applying certain logic. The .awa ...

Discover the process of loading dependent components in Vue.js

Need help with Vue.js: loading components that depend on each other In my router, I'm currently importing components like this: import A from './A'; export default { components : { 'new-comp-A' : NewCompA } } .. ...

Display the Currently Searched Value with Select2

I am currently utilizing the Select2 framework along with an ajax call in my project. I have successfully implemented it, but I am facing an issue where the current search value is being displayed as a selectable option even when there are no search result ...

Placing a MongoDB query results in an increase of roughly 120MB in the total JS heap size

I'm puzzled by the fact that the heap size increases when I include a MongoDB database query in a function within my controller. Here is the code for my router: import { Router } from "express"; import profileController from '../contro ...

How to align scrolling images with their scroll origin - a step by step guide

Curious to know the name of the effect where images scroll in a different orientation than the page, creating a 2D appearance. Take a look at the Google Nexus website and scroll down - do you see the effect? What is this effect called? Is it created usin ...

Which method is better for HTML5/JavaScript GeoLocation: Passing data to a callback function or suspending an async call using promises?

Trying to figure out how to utilize HTML5/Javascript Geolocations effectively for passing location data to an ajax call and storing it in a database. The main challenges I'm facing are the asynchronous nature of the Geolocation call and issues with va ...

Ascending with Progress Indicator Slider

After successfully creating a Bootstrap 5 Carousel with an automated count for each slide (limited to 4) and a corresponding progress bar, I encountered an issue with getting the previous button to function correctly. While clicking the next button works s ...

The error thrown is Uncaught TypeError: 'this' is not defined in the Vuex

<script setup> import { useLayout } from '@/layout/composables/layout'; import { ref, computed ,onMounted} from 'vue'; import AppConfig from '@/layout/AppConfig.vue'; import auth from '@/auth'; const { layoutC ...

Potential absence of value in this Vue 3 component's 'this' placement

I've been encountering an issue with using this.$refs within my Vue component. No matter where I place it - whether in methods, lambdas, or lifecycle hooks - I consistently receive errors indicating that 'this' may be undefined. As a newcome ...

Performance problem with React-Native for-looping through a large array size

I'm currently facing a performance issue with the search function in my react-native app. The search involves scanning through an array of 15,000 elements for specific keywords. Surprisingly, the search performs well and quickly on Android devices, bu ...

Utilizing Object Arrays in Chart.js for Optimal Performance

I'm struggling with using chart.js to create charts for my admin panel. I'm having trouble figuring out how to properly utilize my JSON array of objects in order to generate the correct dataset. What exactly should I be putting in the data field ...

What are the distinctions in how jQuery behaves when an element is assigned to a variable versus in Javascript?

I've noticed that when I assign a jQuery element to a variable, it doesn't match the element in a comparison. However, if I assign a JavaScript element, it does... test1 = $(".the_div"); console.log(test1 == $(".the_div")); // This logs false ...

What is the best way to trigger an ajax request when a user selects a tab?

How can I trigger an ajax call when a tab is clicked by the user? What is the best way to handle the HTML response and display it within the tab? How do I bind JavaScript events to the dynamically loaded HTML content? I am familiar with using jQueryUI tab ...

Problem with jQuery AJAX Request Resolving JSON Data

One thing I have on my first page is this function: <script> function update() { $("#notice_div").html('Loading..'); $.ajax({ type: 'GET', dataType: 'json', data: latestid, url: '2includejso ...

Exploring the Differences between HTML Values in HTML and jQuery

Can someone assist me with comparing HTML values to check for equality? I am looking to compare the values of two select elements in HTML and needing guidance on how to accomplish this. Specifically, I want to determine if the selected values from both s ...

Populate Input Field Based on Dropdown Selection

My goal is to retrieve the value of "hargaJual" when I choose an option. However, when I add a new row to the table and select a different option, only the first row's "Harga" value changes while the second row remains empty. Take a look at the outco ...

What is the best way to dynamically assign classes to a single <li> element in Meteor when an event occurs?

I'm a newcomer to the meteor framework and I'm attempting to create a project where clicking on the name within a <li> element changes the background color to yellow. When another <li> element is clicked, the previous one should rever ...

What steps should be taken to activate eslint caching?

I'm attempting to activate eslint caching by following the instructions in this section of the user guide The command I am using is npm run lint -- --cache=true, and the lint script simply executes a script that spawns esw (which itself runs eslint â ...

When I try to reverse the words in a string, I am not receiving the desired order

Currently delving into TypeScript, I have set myself the task of crafting a function that takes in a string parameter and reverses each word within the string. Here is what I aim to achieve with my output: "This is an example!" ==> "sihT ...

Converting the jQuery $.xajax loadmore feature into a custom XMLHttpRequest JavaScript function

I'm facing challenges while trying to create a XMLHttpRequest loadmore function as compared to using $.ajax. I am uncertain about what I might be missing in my code. Below is the function that is based on a previously working $.ajax version that I ha ...