How can you assign multiple classes to an element based on multiple boolean values using v-bind:class in Vue.js?

I am currently working on a to-do list app and facing a challenge with assigning classes based on boolean values. Although I have successfully achieved this using v-bind:class for some classes, I am now struggling to do the same for another boolean simultaneously.

Here is my current code:

<div
  v-bind:class="[task.checked ? '!bg-gray-800 text-gray-600 line-through' : 'none']"
  v-bind:class="[task.checked ? '!bg-gray-800 text-gray-600 line-through' : 'none']"
  class="tasks_container grid grid-cols-10"
  v-for="task in tasks"
>
  <!-- task for loop -->
</div>
data() {
  return {
    note_text: ' ',
    tasks: [
      {
        text: 'hello',
        checked: false,
        selected: true
      },
      {
        text: 'world',
        checked: false,
        selected: false
      }
    ]
  };
},

In an attempt to address this issue, I tried using :

<div
  v-bind:class="[task.checked ? '!bg-gray-800 text-gray-600 line-through' : 'none']"
  v-bind:class="[task.selected ? '!bg-gray-100' : 'none']"
  class="tasks_container grid grid-cols-10"
  v-for="task in tasks"
>
  <!-- task for loop -->
</div>

This approach failed because it is not possible to have multiple v-bind:class.

I also experimented with:

<div
  v-bind:class="[task.checked?'!bg-gray-800 text-gray-600 line-through':'none'], ['task.selected? !bg-gray-100':'none']"
  v-for="task in tasks"
>
  <!-- task for loop -->
</div>

Unfortunately, this did not work as well, although I cannot recall the specific reason why. If there are any errors in my code, please feel free to point them out. I am new to stackoverflow and would appreciate any help. Thank you!

Answer №1

The Vue documentation provides an illustration of binding classes by utilizing multiple data properties. Here's a way you can structure it:

<div
  :class="{ '!bg-gray-800 text-gray-600 line-through': task.checked, '!bg-gray-100': task.selected }"
  v-for="task in tasks"
>

Answer №2

If you want to meet this particular need, simply provide an object to the v-bind:class directive in order to dynamically switch between different classes.

Here is a demonstration of how it works:

new Vue({
  el: '#app',
  data() {
    return {
      tasks: [
        {
          text: 'hello',
          checked: true,
          selected: true
        },
        {
          text: 'world',
          checked: false,
          selected: true
        }
      ]
    };
  }
})
.text-gray-600 {
 color: gray;
}
.line-through {
  text-decoration: line-through; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div
       v-for="(task, index) in tasks"
       :key="index"
       :class="{ '!bg-gray-800 text-gray-600 line-through': task.checked, '!bg-gray-100': task.selected }"
       >
    {{ task.text }}
  </div>
</div>

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

Using BeautifulSoup to Retrieve JPEG from an Image Tag's Src Attribute

Struggling with scraping this webpage for personal use. I am having trouble extracting the thumbnails of each item on the page. Despite being able to see image tags containing the required .jpgs when using "inspect" to view the html DOM, I cannot find the ...

Guide to creating nested collapsing rows in AngularJS

My attempt to implement expand and collapse functionality in AngularJS for a section is not yielding the desired result. To demonstrate, I created a simple demo of collapsible/expandable sections in AngularJS which works fine. You can view it here. The ex ...

What is the best way to transfer a request parameter from a URL to a function that generates an object with matching name in JavaScript?

I need to figure out how to pass a request parameter from an express router request to a function that should return an object with the same name. The issue I'm facing is that the function is returning the parameter name instead of the object. Upon c ...

"Tailwind - where your brand shines with a sleek, modern logo that stands

I have a specific title width that I need to adhere to, and I'm looking to place a logo after the last word in the title. When the title is too lengthy, it wraps onto a second line. For example: My Title (insert logo here) Check out this CodePen us ...

JSON formatting error, an unexpected colon was encountered

I have a JSON file that contains various recipes for different meals categorized by their purpose of either losing weight or gaining weight. { "breakfast": { "lose": [ { "name" : "F ...

Show singular array element upon click

I need help with a specific task. When a button is clicked, I want to display a random item from an array. Each array item should only be displayed once. Currently, my code is set up as follows: When the button is clicked, a random array item is displ ...

Verifying the authenticity of a Stripe discount code

My goal is to allow users to apply a coupon code on my website, triggering a check in the Stripe dashboard. Currently, I have implemented the following code snippet, but I am facing an issue with transferring the validCoupon data from the client side to th ...

Updating the language of the months displayed in the popup calendar

I am attempting to change the language of the clickDate function from English (Jan, Dec, etc.) to another language. However, I am struggling to find a way to do so because I only have access to the scripts provided below. The idate is in the format 2015073 ...

Is it possible to update the CSS file of an external SVG file in real-time?

Is there a way for an SVG image to reference another CSS file? A webpage contains an SVG file. A button allows users to switch between classic colors and high contrast mode on the entire webpage, including the SVG image. Attempt w.css (white backgrou ...

When using React Router with Suspense for lazy loading, my notFound page consistently displays beneath all of my components

I have a component that generates dynamic routes using a list called routes[], but whenever I add the route for the "not found" page NotFoundUrl, it always displays it in all components. All the other routes work perfectly fine, but when adding the 404 ro ...

Utilizing various ExtJS selectors

Can Ext JS 4 support multiple selectors for event handling? I understand that in JQuery, you can achieve this by using the following syntax: $('.selector1,.selector2').click(function(){ //.. }); However, I attempted to use a similar method ...

Error Alert: Duplicate Status Detected While Posting on Twitter via API

I am delving into the world of JavaScript for the first time and using Node.js in conjunction with the Twitter API to enhance my coding skills. To facilitate this learning process, I have incorporated the Twit NPM package into my project. My goal is to dev ...

Building a simple doughnut chart with D3.JS and Vue - a beginner's guide

In my Vue project, I attempted to create a simple Doughnut chart following the example provided in the D3.js documentation: Doughnut Chart. However, I encountered an issue while trying to implement this chart in Vue. Every time I attempt to get it to work ...

attempting to retrieve numerical variable beyond the function in jQuery

Trying to implement a star rating system and need to access the rating number for further actions. How can I make the number variable accessible outside of the click function? $(document).ready(function () { $(".li").mouseover(functio ...

How can I delay the execution of "onAuthStateChanged" until "currentUser.updateProfile" has completed?

Currently facing an issue with registering users in my Vue app. When a user registers, I need to trigger the updateProfile function to add more user data. However, the problem arises when the onAuthStateChanged function in my main.js is executed before the ...

Retrieving authorization token from axios

Is there a way to dynamically access a bearer token stored in localStorage for authentication purposes? const apiClient = axios.create({ baseURL: 'http://localhost:5000/api/v1', withCredentials: false, headers: { Accept: 'applicat ...

Appears as though time is slipping away during date conversions

I seem to be experiencing a strange issue where I lose a day when transitioning between MySQL and my JavaScript code, and I can't seem to figure out why. When I insert a date into the database (for example, 10/14/12), it appears as 10/13/12 in the dat ...

Issues encountered while attempting to use JSON in a JavaScript AJAX call

Hey there, I need some help with an issue I'm facing in my AJAX request. I have text data returning and I'm trying to convert it to JSON using json_parse, but for some reason it's not working. The returned data from the AJAX request looks s ...

I implemented React-Router to navigate to a different page upon clicking a link, however, the redirection is not working as expected

This is my main.js file import React from 'react' import Quote from './components/Quote'; import './index.css' import Abraham from './components/Abraham' import { BrowserRouter as Router, Routes, Route, Link ...

Is it possible to manipulate videos embedded in an iframe using javascript?

It's common knowledge that JavaScript commands from Google can be used to control YouTube videos, while Vimeo provides its own JavaScript commands for their videos. Both videos are typically embedded within 'iframes' on websites. I'm ...