Ways to switch classes within a loop of elements in vue.js

I'm just starting to learn vue.js and I'm working on a list of items:

<div class="jokes" v-for="joke in jokes">
    <strong>{{joke.body}}</strong>
    <small>{{joke.upvotes}}</small>
    <button v-on:click="upvote"><i class="fa fa-arrow-up grey"></i></button>
<div>

My goal is to change the grey color to green when the user clicks the upvote button, so they can easily see which jokes they have upvoted.

In my methods section, I currently have:

  data () {
    return {
        jokes:[], //populated dynamically from the backend server
        id: ''

    }
  },

methods: {
    upvote: function(joke) {
        joke.upvotes ++;
        //How can I toggle from grey to green here?
    }
}

Can anyone help me figure out how to achieve this? I've tried several methods but all the tutorials seem to change the class for ALL items rather than just the one that was upvoted.

Answer №1

To start, make sure you pass the joke to the method.

v-on:click="upvote(joke)"

Next, add a v-class to it using either v-bind:class or just :class.

<div class="jokes" v-for="joke in jokes">
  <strong>{{joke.body}}</strong>
  <small>{{joke.upvotes}}</small>
  <button v-on:click="upvote(joke)"><i class="fa fa-arrow-up" :class="{ green : joke.upvotes>0, grey: joke.upvotes<=0 }"></i></button>
<div>

VIEW EXAMPLE HERE

If you want the upvote action to only affect the one you clicked on, add a property called "selected" to the joke object to track this information. For example:

joke.selected

Then modify your code like this:

<div class="jokes" v-for="joke in jokes">
  <strong>{{joke.body}}</strong>
  <small>{{joke.upvotes}}</small>
  <button v-on:click="upvote(joke)"><i class="fa fa-arrow-up" :class="{green: joke.selected, grey: !joke.selected}"></i></button>
<div>

Update your method as follows:

upvote: function(joke) {
   joke.upvotes++;
   if(!joke.selected){
        joke.selected=true;
   }

}

VIEW UPDATED EXAMPLE HERE

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

Having trouble extracting the video ID from a Youtube feed XML with jQuery

My goal here is quite simple - I have created a search result using a URL string with the YouTube API. When you visit the URL, you can view the XML returned without any issues. The specific URL is: https://gdata.youtube.com/feeds/api/videos?q=all the smal ...

Attempting to showcase data retrieved from various API calls

I am currently facing an issue where I am retrieving stock/share names from my MongoDB database and attempting to display their prices by making API calls for each of them in my component. However, I am only receiving the price for the last stock. Below i ...

Getting the result from a JavaScript request, whether it's synchronous or asynchronous

This code snippet involves a function that starts with a synchronous comparison test == 0. If the comparison is true, it returns one piece of content; however, if it's not, an asynchronous request is made. The goal here is for the latter part to retur ...

Node Js seems to be taking quite a while to output to the console

Hello, this is my first time posting on Stack Overflow so please bear with me if I make any mistakes. I created a button that, when clicked, decrements the quantity by one. After updating the UI, I send the data to the server. However, when I console log t ...

Encountered an error searching for module 'autoprefixer' while executing the npx tailwindcss init -p command

I am currently working with Vue 3 and attempting to integrate tailwindcss by following this helpful tutorial: https://tailwindcss.com/docs/guides/vue-3-vite#install-tailwind-via-npm I have successfully installed the necessary dependencies using the comman ...

Encounter the error message "Socket closure detected" upon running JSReport in the background on a RHEL system

I'm encountering an issue with JSReport at www.jsreport.net. When I run npm start --production in the background, everything seems to be working fine. But as soon as I close this session, an error pops up: Error occurred - This socket is closed. Sta ...

What is the way to display the final list item when clicking in jQuery?

I am attempting to achieve a specific behavior where clicking on a button will trigger the content below to scroll in such a way that only the last item in the list is visible. I have been using jQuery for this functionality, but unfortunately, it is not ...

The Chrome application does not retain cookies

Why is the cookie url_user not being stored? Below is the content of index.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial- ...

Instructions for populating a DataTable with JSON data while allowing for editing of rows

Hey there, looking for some expert advice, I've been experimenting with the datatable plugin and I'm curious if it's feasible to populate a table with row editing actions using ajax? This is the code snippet I currently have. It successfull ...

Error encountered while trying to display the react-bootstrap table

I am having trouble rendering sample data using react-bootstrap tables. Every time I try, I encounter the error: TypeError: Cannot read property 'filter' of undefined I've searched on various platforms and visited multiple links, but I ca ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

Can we safely save a value in session storage directly from the main.js file in Vue?

Throughout the user session managed by Vuex, I have a session storage value set to false that needs to be monitored. Setting up this value directly from the main.js file looks like this: import { createApp } from 'vue'; import App from './Ap ...

The <NuxtLink /> element does not function the same as an anchor tag for creating internal links

I have a link defined in my Nuxt pages like this: <NuxtLink to="/#section-x">Section X</NuxtLink> The link is included in the menu on my global layout file. When I try to click the link from a page that is not the root page (/any-path), it ta ...

What is the relationship between directives, templates, and ViewContainers in Angular?

I have implemented a basic functionality in my component where numbers are injected after a delay using a custom directive called *appDelay It is known that the Angular syntax hints with * will de-sugar into something like this: <ng-template ...> .. ...

Determining if an emitted event value has been altered in Angular 4

I am currently working on an Angular 4 project. One of the features I have implemented is a search component, where users can input a string. Upon submission of the value, I send this value from the SearchComponent to the DisplayComponent. The process of ...

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

Customizing AngularJS directives by setting CSS classes, including a default option if none are specified

I have designed a custom directive that generates an "upload button". This button is styled with bootstrap button CSS as shown below: <div class="btn btn-primary btn-upload" ng-click="openModal()"> <i class="fa fa-upload"></i> Upload & ...

Leverage the power of Web Components in Vue applications

Currently, I am attempting to reuse Web Components within a Vue Component. These Web Components utilize the template element for formatting output. However, when I insert them into the Vue Template, they are either removed from the DOM or compiled by Vue. ...

Discovering checkboxes in HTML using jQuery

Greetings! I have limited knowledge when it comes to using jQuery. I am currently facing an issue with the Checkbox attribute. Below, you will find the code snippet that I have mentioned: Code: $( this ).html() Output: <input name="cb_kot[]" class= ...

Issues encountered when implementing server-sent events in a project built with Node.js and React

I've been working on implementing server-sent-events into my Node.js and React application. After doing some research and following tutorials online, I found this particular site to be very helpful and straightforward. The main objective is to have a ...