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

Performing an AJAX call every half-hour using JavaScript

I am looking to implement an ajax request every 30 minutes using JavaScript. Specifically, for the user currently logged in, I aim to retrieve any notifications that have a start date matching the current time. These notifications are set by the user with ...

Is it possible for a memory leak to occur in node.js when using new Date()?

For this particular case, when updating an existing MongoDB document with new Date() causing a potential memory leak is a question that arises. One might wonder if allocating a new object with the new keyword necessitates manual deallocation to prevent lea ...

Using JavaScript for Array manipulations

Here's a string that I want to convert into an array: "["Arr1","Arr2"]" To achieve the desired format, I need to remove the first and last characters so it looks like this: ["Arr1","Arr2"]. I've attempted using the slice function in this wa ...

The array element is not being shown in the id "main" when using a for loop with the onchange function

I've been using document.write to display specific content, but it seems to be removing other elements from the page. Is there a way for me to display this loop inside the element with id="main" without losing any content? When I attempt to use docume ...

apostrophe cutting off a portion of the input field's value

I am facing an issue with a reloaded input box on a web page that is updated through an ajax call. Whenever the input contains a single quote, the rest of the value gets cut off. How can I resolve this problem? The value assigned to myVal dynamically from ...

Having trouble with the installation of go get wails?

Attempting to implement golang and wails, but encountering issues after executing the following command: go get github.com/wailsapp/wails/cmd/wails Resulting in errors such as: ../../github.com/wailsapp/wails/cmd/semver.go:21:3: cannot use semverVers ...

Encountering difficulty retrieving the value of a hidden input with jQuery's find method

When a user clicks on the delete icon, I want to retrieve the value of the hidden input inside the "delete" class. However, I am getting an undefined result. Can someone please guide me on where I might be going wrong? <table class="items-list"> ...

The console does not display the JSON data for requests and responses

I have successfully set up a server inside of VSCode, but unfortunately the request and response logs that I usually see in my terminal when running the server with npm start are not appearing. I would really like for them to display in the Debug Terminal ...

What is the best way to create a JavaScript array after fetching data from an AJAX request that returns a JSON array?

When I make an ajax call that returns JSON data, my goal is to extract and organize this data into a new JavaScript array through looping. This is a snippet of the JSON data returned: { query: [ ], products: 
[ 
{ title: "title 1", ...

Connecting a string array to the navigation bar

Need Assistance with AngularJS: In my controller, I have a string array that looks like this: var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About&apos ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

Selecting a Child Component in Vue.js: A Guide to Specifying the Correct Component

Within my application, I have a variety of components that are either generic or specific to certain brands. For example, I have two brand-specific components named Product_brand_A.vue and Product_brand_B.vue, both of which I want to display in a list form ...

Error: The function coolArr.printArray is not defined in the npm package being imported

My custom package contains an index.js file with the following code: module.exports = class CoolArray extends Array { printArray() { console.log(this); } } After transpiling the code using es2015 syntax with Babel, I connected the package to my te ...

Replace Jade script with block override

Having trouble overriding a Jade script. tag, nothing seems to work. Here is the code snippet: Layout.jade block foot footer.container#footer .row .twelve.columns All rights reserved. &copy; 2015 Pet Feeder block scripts ...

What is the best way to update a form after it has been submitted?

i have a form that looks like this <form id="abc"> <div> <select > <option id= "1"> ha1 </option> <option id= "1"> ha2 </option> <option id= "1"> ha3 </option> <option id= "1"> ha4 </option> ...

Unable to trigger Vuejs click event when using v-if condition

I've encountered a strange issue. I'm attempting to trigger a method when an element is clicked in a v-for loop, but it doesn't seem to work when using v-if or v-show. Here's a sample of my HTML code: <div class="chosen-drop custom ...

What is the best way to generate a new DIV every time a button is clicked?

I am attempting to make a square DIV that is red and measures 100x100 pixels. Each time a button is clicked, I want the square to be created. However, the code I have written is not functioning properly: <html> <title> Create New Div ...

Utilize Node.js and an API to generate a new problem in GitHub, but encountering an issue where the response

I have been experiencing an issue related to making a Post request to the Github API for creating an issue. I have gone through this post on Stack Overflow but I am seeking assistance in using the request module. Although I have referred to the Github docu ...

Highlighting a Table Column with a Radio Button

I am struggling with controlling the highlight of a table using only radio buttons. When I try to change the selector to input:radio, it doesn't work as expected. It seems to only work with the selector provided in my code snippet. $("th").on("clic ...

Scroll the div back to the top when the form is submitted

I have set up a form in a pop-up using Bootstrap modal. The form is quite long, so after submission, the message appears at the top of the form. However, I want it to scroll to the top when the user submits the form so they can easily see the message. Is ...