Vue: Implementing conditional styling in table cells

Currently, my vue function involves using nested v-for loops to iterate through an object and create a table with rows and cells. While this method is effective, I am now faced with the challenge of implementing a v-if statement in the innermost loop to consider the `discarded` value for conditional styling.

Specifically, I need to examine the `tests.discarded` value for each `td` element and based on whether it is greater than 0, assign either a red or green color to the cell.

Is there a way to achieve this within the existing structure of my code? It seems that using a v-if within the innermost v-for loop is not a feasible option.

namestest: [
  name: "john",
  date: "08/12/21",
  discarded: 4,
  count: 19
]

<tr v-for="(tests, name) in namestest" :key="name">
    <td>@{{ name }}</td>
    // For each iteration, we need to check if the discarded value is greater than 0 and then apply the appropriate styling
    <td v-for="date in dates" :key="date">@{{ tests[date] && tests[date].count }}</td>
</tr>

Answer №1

Avoid using v-if when applying styles conditionally in your code:

<td :style="'background: ' + (tests.discarded > 0 ? 'red' : 'green')">@{{ name }}</td>

Answer №2

One option is to implement @slauth's solution using an inline expression within the style attribute, or you can opt to create a method or function.

Regardless of whether you choose to utilize the Option API or the Composition API, you just need to define a function that accepts a parameter (even if it's discarded). You could also define multiple methods - one for styling color and another for conditionally rendering text.

When it comes to inline conditions, you can always use

<template v-if="something">
- content within the template tags will be displayed, while the template tags themselves will not.

Answer №3

One possible way to achieve this is:

<td>@{{ name }}</td>
<td v-for="date in dates" :style="'background: ' + (tests[date].discarded > 0 ? 'red' : 'blue')" :key="date">@{{ tests[date] && tests[date].count }}</td>

You can also incorporate the conditional logic within the class binding rather than the style attribute. For example:

<td v-for="date in dates" :class="{ badcell: (tests[date].discarded > 0) }">@{{ tests[date] && tests[date].count }}</td>

By doing this, the badcell class will only be applied if the value of discarded is greater than 0. You can then define the styles for the new 'badcell' class in your CSS or SCSS:

td.badcell {
    background-color:red;
    font-weight:bold;
}

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

Maximizing Efficiency: Top Techniques for Emphasizing Grid Rows with jQuery

Currently, I am facing an issue with the jQuery code I am using to highlight the selected row in my grid. It seems to be taking longer than anticipated to select the row. Does anyone have suggestions on how I can optimize this code for better performance? ...

What is the best way to customize the styles of Material UI V5 Date Pickers?

Attempting to customize Mui X-Date-Pickers V5 through theme creation. This particular component is based on multiple layers. Interested in modifying the borderColor property, but it's currently set on the fieldset element, so need to navigate from Mu ...

Issue with Webpack: file-loader failing to load SVG files dynamically in HTML

Configuration in package.json: { "name": "webpackTutorial", ... "devDependencies": { "bootstrap": "^4.3.1", ... "webpack-merge": "^4.2.2" } } Webpack Configuration in webpack.common.js: var HtmlWebpackPlugin = ...

Structure of a GraphQL project

What is the most effective way to organize a graphQL project on the server side? Here is my current project structure: src config models setup schema queries index userQuery resolvers index userRes ...

Strategies for managing large numbers within WebGL GLSL shader programs

What is the best approach to handle large numbers like the one provided in GLSL? I have a shader that requires Date.now() as a uniform, which is defined as: The Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 ...

The Axios API request is made, but fails to retrieve any data back to the client

I've been working on a feature in my VueJS app where I need to restrict page viewing of an Upload instance to only members of a specific Group. However, I'm facing an issue with retrieving the group information. Despite axios successfully hittin ...

Why does parsing the GET response fail intermittently with Jquery, ajax, and JSON?

Currently, I am encountering an issue with ajax calls using jQuery where the response being returned is a JSON array. In certain scenarios, everything works perfectly fine. However, in other cases specifically in browsers like Firefox and IE11, there seems ...

Animations are failing to run within a Bootstrap card when using Vue rendering

I have utilized Bootstrap cards to display pricing information in my project. I implemented a collapse feature for half of the card when the screen size is equal to mobile width. While using vanilla Bootstrap, the animation worked seamlessly with the col ...

Storing user credentials in Firestore after registration - best practices

Hi, I need some assistance with storing user credentials in Firestore after they sign up. Unfortunately, I keep encountering the following error: Invalid collection reference. Collection references must have an odd number of segments, but userDatabase/QMJ ...

List Elements Not Displaying Correctly due to CSS Styling Issues

After spending several hours trying to solve this problem, I've hit a roadblock. The challenge lies in dynamically adding items to a list using JavaScript and the Dojo library. I've experimented with both vanilla JS and Dojo code, ruling that pa ...

Is there a way to extract subtitles from a javascript-controlled webpage using Python?

I am attempting to scrape information from this website: Link to Website Specifically, I am trying to extract the title ''Friday Night Lights'', but I am encountering difficulties accessing it due to JavaScript on the site. To achieve ...

Issues with merging styles in TinyMCE 4

I've exhausted all the current configuration options and I'm still unable to resolve this issue. My goal is to have the style tag appended to the selected element without generating an additional span. For example: <p>Hello World!</p> ...

Customizing the layout of specific pages in NextJSIncorporating

In my Next.js project, I'm trying to set up a header and footer on every page except for the Login page. I initially created a layout.tsx file in the app directory to apply the layout to all pages, which worked fine. However, when I placed another lay ...

Converting JSON data to HTML using Handlebars

Can you assist me in transforming the following JSON data into a table with 3 columns: property name, property source, and property value? "result": { "total": 100, "config": { "propName1": { "source": "propsrc1", ...

What is the best way to ensure the constant rotation speed of this simple cube demo?

Currently delving into the world of Three.js. I'm curious about how to make the cube in this demo rotate at a consistent speed rather than depending on mouse interactions. Any tips on achieving this? ...

Unable to confirm form validation with Vue

Recently, I started working with Vue and encountered a problem while running the code below. The error message "ReferenceError: $vAddress is not defined" keeps popping up. Despite my efforts to search for solutions online, I couldn't find any that add ...

Creating a Vue2 modal within a v-for loop to display a dynamic

Recently, I've been working on implementing a vue2 modal following the instructions provided in the official Vue documentation at https://v2.vuejs.org/v2/examples/modal.html. The code snippet I have been using looks something like this: <tbody v-i ...

The ng-model directive in drop-down selection elements

I have a series of questions along with their answers, and I want the user to select an answer from a drop-down menu. How can I achieve this? I've attempted the following code, but the select option isn't appearing on the screen. HTML: <div ...

Implementing conditional color parameter using Vuetify on an element

In my Vuetify project, I'm utilizing the built-in color parameter and predefined colors. My goal is to dynamically change the component's color based on the data it receives. For example, if complete: true, then the color should be green. Here&a ...

Within Blade, Laravel and Vue components are able to communicate by sharing data from one component to another

Is it possible to achieve this task? Here is the scenario: I have a left navbar displaying membership status (active/inactive). Once the payment gateway receives the payment, a webhook is triggered via Paddle(Laravel Paddle API). During the webhook proc ...