What steps are needed to switch colors after a loop has been clicked?

I have a loop setup like this:

data: {
  show: false
}
.test {
  hight: 10px;
  background-color: red;
}

.test2 {
  hight: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div v-for="value in data" :key="value.id">
  <div class="test" v-bind:class="{ test2: show }" v-on:click="show = !show">
  </div>
</div>

When I click any div, the height of all the divs changes from 15 to 10 or vice versa.

However, I would like to only change the height of the div that was clicked. How can I achieve this?

Answer №1

In order to achieve the desired effect, it is necessary to include a show variable for every element:

new Vue({
  el: "#app",
  data: {
      show: [],
    items: []
  },
  created() {
    fakeFetch().then((items) => {
       this.items = items;
       this.show = this.items.map(() => false);
    });
  },
  methods: {
    isShown(i) {
        return this.show[i]
    },
    changeShow(i) {
        Vue.set(this.show, i, !this.show[i]);
    }
  }
})

function fakeFetch() {
  return new Promise((resolve, reject) => {
     let count = Math.floor(Math.random() * 20) + 1;
     let result = [];
     for (let i = 0; i < count; i++) {
       result.push({ text: Math.random() });
     }
     resolve(result);
  })
}
.test {
  height:10px;
  background-color: red;
  margin: 10px;
}
.test2 {
  height: 35px;
 }
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b3d3e2e0b79657e657a7d">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <h2>Items:</h2>
  <div 
  class="test" 
  :class="{ test2: isShown(index) }"
  @click="changeShow(index)" 
  v-for="(item,index) in items" :key="index">
  </div>
</div>

P.S. To simplify the process of managing visibility using the show array, consider creating each element as a component and controlling visibility internally with a single show variable.

Answer №2

To easily manage the active state, you can set an active variable and apply a specific class when it matches the current button index.

<div v-for="(value, index) in data" :key="index">
  <div class="some-class" :class="{'active-class': index === active}" @click="active=index"></div>
</div>

.....

 data: function () { 
  return { 
    active: undefined
  }
 }
 

Answer №3

To make more specific changes, it's recommended to use a separate variable for each item rather than one variable controlling the class of every item.

If you have control over the displayed data, consider organizing it like this

data: {
  items: [{id: 1, visible: false},
          {id: 2, visible: false},
          {id: 3, visible: false}]
}

and modify the visibility attribute instead of using a global show variable.

If you don't have control over the data, creating a computed property might be a viable option.

You can test out this approach on the following codepen link: https://codepen.io/anon/pen/ejmdPX?editors=1111

Answer №4

To specify the class you desire, implementing a method would be beneficial.

When executing v-on:click="myFunc()", an event is triggered allowing alterations to be made on the targeted element.

methods: {
  myFunc (event) {
    event.target.classList.toggle("test2")
  }
}

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

I'm having trouble locating my route for some unknown reason

I've set up a basic code structure to test my routes, but I keep getting a 404 error. Although I have an app.all function to catch errors, I'm having trouble pinpointing where the issue lies. Below is my index.js file, where I've configured ...

What is the reason behind using 'dummy' local variables to define return object keys?

I've come across a code similar to the one below on several occasions recently. One thing to observe is that modelMapper, viewMapper, and source are all defined as local variables but are not used anywhere else, except for being keys in the return ob ...

Is there a substitute for AngularJS $watch in Aurelia?

I'm in the process of transitioning my existing Angular.js project to Aurelia.js. Here is an example of what I am trying to accomplish: report.js export class Report { list = []; //TODO listChanged(newList, oldList){ ...

Is the Child-Parent-Communication Method Lost?

I'm currently working on setting up communication between child and parent components in nuxtjs. Here is my child component: <div> <b-nav-item @click="clicked" :class="{active: active}">{{item.name}}</b ...

The JSON.parse function encounters issues when trying to parse due to a SyntaxError: Unexpected character found after JSON at position 2, causing it to be unable

I've encountered an issue with my JavaScript code when trying to retrieve the value of the details field from JSON data. While all other values are successfully passed to their respective fields, the details field generates the following error: "Unabl ...

Establishing the focal point and emphasis within a textarea input field

I am presenting a textarea input through PHP with the following command : print " '<textarea rows='16' cols='30'>$flist'</textarea><BR>"; I want the textarea to receive focus and automatically select the co ...

Data Binding in AngularJS appears to be non-functional

Experimenting with AngularJS, I created a small code snippet that doesn't seem to bind data properly. Here is the HTML and JS code for those who prefer not to visit the provided link: first.html <!doctype html> <html ng-app="firstApp"> & ...

Customizing the Switch component individually for each item fetched from an API in React Native

I'm struggling with setting the switch button individually for each item in my API. Despite trying multiple solutions, none of them seem to work for me. const results = [ { Id: "IySO9wUrt8", Name: & ...

Currently focused on developing vertical sliders that can be manipulated by dragging them up or down independently

https://i.stack.imgur.com/NgOKs.jpg# I am currently working on vertical sliders that require dragging up and down individually. However, when I pull on the first slider, all sliders move together. The resetAllSliders button should also work independently, ...

Unable to save object in JavaScript memory

Currently, I am in the process of implementing a Stack in JavaScript using a LinkedList. However, I encountered an issue when trying to instantiate a Node class. When attempting to create a variable let newNode = new Node(x), I am receiving undefined. I a ...

Generating output from a callback function in TypeScript

When I execute a graphql query, the showUsers function is supposed to display all users (styled as boxes). However, at the moment, nothing is showing up. I am utilizing a functional component instead of a class component. This function is invoked after m ...

How to upload numerous chosen files from an Android device using PHP script

When attempting to upload multiple files using the file selection option on an Android mobile device, I encountered an issue of not being able to select specific multiple files. I tried utilizing the multiple-form/data and multiple="multiple" attributes w ...

Leverage promises to alter reactive data, strategically placing them to minimize the frequency of triggers being activated

Initial Method const list = reactive([1, 2, 3, 4, 5]); const clickHandler = () =>{ list.push(...[11, 12, 13, 14, 15]); list.push(...[16, 17, 18, 19, 20]); Promise.resolve().then(() => { list.push(33) ...

Control and manage AJAX POST requests in the controller

I'm currently working on implementing an ajax post request feature in my project. The goal is to have a button on my html page trigger a javascript event listener, which then initiates an ajax post request to receive some text data. However, I seem to ...

Ways to showcase information from an angular service

I'm struggling with displaying data from a service in my HTML view using AngularJS. My goal is to show a list of submitted forms called Occurrences in the view. When clicking on a list item, I want to be able to view all the data fields submitted thro ...

Top destination for verifying permissions in vue.js

Within my Laravel/vue.js application, the initial page load results in a structure like this: <script> window.settings = {}; window.settings.user = {}; window.settings.user.timezone = 'Europe/Moscow'; w ...

Ember controller failing to update template upon property set within promise execution

I am facing an issue while integrating user login functionality in my application. After retrieving the user data from the server, I aim to display the user's name on the page once the process is completed. The login form appears as a popup window, in ...

Using a function parameter to restore the values of an array

Looking to clear an array using a function parameter. Below is my implementation: <script> fruitArray = ["apple", "banana", "orange", "pineapple"] function clearFruitArray(myArr){ myArr = []; ...

Steps to create a zigzagging line connecting two elements

Is it possible to create a wavy line connecting two elements in HTML while making them appear connected because of the line? I want it to look something like this: Take a look at the image here The HTML elements will be structured as follows: <style&g ...

The compilation of PKG using Axios 1.x encounters an error

Despite attempting numerous strategies, I have not been successful. I developed a Node.js application with API requests managed using axios. However, I am unable to convert it into an executable file. Trying to downgrade Axios to version 0.27.0 resolved th ...