Changing the active state of an icon when clicked in a list generated by v-for in Vue

In my Vue.js application, I have created a list of objects where each object represents a star. I want to implement a feature where a star changes color when it is clicked.

However, the issue I am facing is that when I click on one star, all the stars in the list change color simultaneously.

To demonstrate this problem, I have created a dummy example on JSFiddle: https://jsfiddle.net/t3f0rpqh/21/

Although I intend to use Font Awesome icons for the stars, I am encountering the same problem. Whenever I click on one icon, all the icons in the list are affected, rather than just the one that was clicked.

 <font-awesome-icon
  :class="{ activeIcon: activeIcon}"
  :icon="icon"
  v-on:click="starLocation(item.id)"
 />

I am seeking guidance on how to bind each star/icon to a specific object or how to ensure that only the clicked star/icon changes color.

If anyone has any insights or solutions to offer, I would greatly appreciate it!

Thank you for your assistance!

Answer №1

To resolve this issue, ensure to include the activeIcon property for each todo item and manage their toggling individually as shown below:

data: {
   todos: [
    { text: "Master JavaScript", id: "Location4", activeIcon: false },
    { text: "Explore Vue", id: "Location3", activeIcon: false },
    { text: "Experiment with JSFiddle", id: "Location2", activeIcon: false },
    { text: "Create something amazing", id: "Location1", activeIcon: false }
  ]
}    

Additionally, update the toggleIcon method as follows:

toggleIcon(id) {
  try {
     var item = this.todos.find(t => t.id === id)
     item.activeIcon = !item.activeIcon;
  } catch (error) {
    alert(error);
  }
}

Finally, modify your template code to reflect the changes:

<p 
  @click="toggleIcon(item.id)"
  :class="{ activeIcon: item.activeIcon}"
  :key="item.id"> TOGGLE ICON
</p>

View Demo

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

What is the best way to generate a nested object arrangement using a path (series of keys)?

I have a challenge of creating nested objects from arrays of strings to store the sequence of input strings. Originally, I was only generating chains with a depth of 2, but now I need to expand this capability to create higher-depth chains. Essentially, I ...

Typescript - Conditional imports

When working with the moment-timezone module, one issue that arises is receiving a warning if it is included multiple times. In my specific case, I have a module that necessitates the use of this timezone functionality. Since I am unsure whether or not the ...

The utilization of count variable is not permitted in embedded array lookup

I've been using C# for quite some time, but I'm facing a challenge with a basic concept in the JavaScript part of my project. The following code snippet is part of a larger function I've written: addPaymentsToBreakdown = function () { f ...

The express-fileupload throws an error saying "ENOENT: unable to locate the file or directory at 'public/images/name.ext'"

I am encountering an error ENOENT: no such file or directory, open 'public/images/name.ext from express-fileupload. I have searched for solutions to this issue, but none of the ones I found seem to work for me. Here are two examples: No such file or d ...

Receiving Null Value Upon Asynchronous API Call Before Data Retrieval

Struggling with Fetching and Displaying API Data in a Table I am facing a challenge where I need to fetch an API multiple times and populate the data into a table. The issue arises when the data for a specific year is not available, causing the table to b ...

Ensure that the array in Jest does not have any falsy values present

Attempting to utilize Jest for a unit test to ensure the absence of falsy values in my array named values. Unfortunately, the initial approach is not effective; the test actually passes: const badValues = ['', null, undefined, false, {}, []]; e ...

Tips for parsing JSON using JavaScript

I am looking to iterate through a JSON object that looks like {"key1":"val1","key2":"val2","key3":"val3"} in a loop. Here is my attempt: var inobj = '[{"key1":"val1","key2":"val2","key3":"val3"}]'; var obj = eval(inobj); for (var i = 0; i ...

What is the best choice for managing state storage and retrieval when working with React, React Router, and React Relay?

As I navigate through my app using React, React Router, and React Relay, I encounter different ways of handling data updates. React offers useState, React Router has its pushState wrapper (location.state), and Relay utilizes the updater() method. However, ...

Pressing the submit button within a form in Ionic2 triggers the Ion-Input onSubmit event

In my form, there is an ion-button and an ion-input included. The ion-button is not meant for submitting the form. When I try to edit a value in the input field and press "ok", I expect the keyboard to hide. However, the ion-button reacts to this event an ...

Activate the class when clicked

I am facing a minor issue with the JavaScript onClick function. I need a function that will target a specific class, like .modal. Currently, it looks like this <div class="modal" onclick="modalFix()"> <p>here is some text</p> </div> ...

Tips for Organizing an Array: Grouping Categories and Products

I have a single array and I am looking to separate categories from the products listed within it. const product = [{ id: 1, name: 'Cloth', cat: ['fashion', 'man', 'women'] }, { id: 2, name: &apos ...

What is the method for dynamically updating and showcasing a JSON file upon the click of a button?

I'm currently developing an add-on that will display a panel with checkboxes and a save button when a toolbar button is clicked. The goal is to allow users to select checkboxes, then save the selected data in a JSON file that can be accessed and updat ...

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

Is it possible to manually trigger a refresh/render for a specific URL in Vue.js?

When accessing the URL "example.com/abc", is it feasible to have the page reload instead of updating the DOM? All other URLs should function as normal, but for /abc in particular, the page should refresh or re-render. ...

Guide on triggering an open modal when clicking a link using jQuery

Creating a modal popup has always been my goal. After designing the CSS to style it, I found myself stuck as I lack knowledge in JQuery or JavaScript to code the functionality that animates and opens the modal upon clicking a button or link. Despite search ...

Having trouble removing or adding a class to an HTML element?

I have a collection of three colored buttons. My goal is to allow users to select one button at a time, triggering it to be highlighted while the others are unselected. Each button corresponds to an object with a property called isSelected that can be set ...

What are your thoughts on utilizing for loops within the same function in Vue to organize fetched data?

Currently, I am implementing a fetch request to retrieve data from an API. The data is then converted to JSON format and I would like to organize it into separate categories. For instance, tickets with the status "active" should be placed in one array whil ...

What is the best way to develop shared singleton components that work seamlessly across various platforms?

How about developing a React component called LoadingMask that can toggle the display of a loading mask based on the current state? The purpose would be to show the mask before an ajax call and hide it once the data is received. To avoid showing multiple ...

Having issues with images not loading and receiving a 401 error with the API while using Vite in a production build

While working on my React project with Vite, I've encountered a few challenges during the production build process. Everything seems to be running smoothly when I use npm run dev, but when I try to build the project using npm run build and then previ ...

The jquery selector fails to retrieve all elements

On the upcoming web page, I am attempting to use Jquery to select all <li> elements. Specifically, I want to target all the products contained within <ul class=search-result-gridview-items">. You can find the products here: I have made attempt ...