Using Vue.js to dynamically assign CSS classes based on variables

Is it possible to achieve this with a dynamic class like the following?

<div :class="'outofstock.item_' + item.id ? 'bg-green-500' : 'bg-red-500' ">
I have been struggling to find the correct syntax for this. Thank you for any answers.

This is an example of what I am trying to accomplish. I need the result outofstock.item_1, outofstock.item_2, and outofstock.item_3 in the :class attribute.

<template>
<ul>
    <li v-for="item in items">
        <div :class="'outofstock.item_' + item.id ? 'bg-green-500' : 'bg-red-500' ">
            {{ item.name }}
        </div>
    </li>
</ul>
</template>

<script>   
    export default {
        data () {
            return {
                items: [{id: 1, name: 'monitor'}, {id: 2, name: 'printer'},{id: 3, name: 'scanner'],
                outofstock: {item_1: false, item_2: true, item_3: false}
            }
        }
    }
</script>

Answer â„–1

This code snippet demonstrates how to achieve a specific styling effect in Vue Playground without the need to call a method:

Check out the Vue Playground for more information.

<template>
  <ul>
    <li v-for="item in items">
      <div :class="outofstock['item_' + item.id] ? 'bg-green-500' : 'bg-red-500' ">
        {{ item.name }}
      </div>
    </li>
  </ul>
</template>

<script>
  export default {
    data() {
      return {
        items: [{ id: 1, name: 'monitor'}, { id: 2, name: 'printer'}, { id: 3, name: 'scanner'}],
        outofstock: {
          item_1: false,
          item_2: true,
          item_3: false
        }
      }
    }
  }
</script>

<style>
  .bg-green-500 {
    background-color: green;
  }
  .bg-red-500 {
    background-color: red
  }
</style>

Answer â„–2

Create a computed property that generates a function accepting the item ID as an argument, then utilize string literals to display the appropriate class:

<template>
<ul>
    <li v-for="item in items">
        <div :class="`${fetchItemStatus(item.id) ? 'bg-green-500' : 'bg-red-500' }`">
            {{ item.name }}
        </div>
    </li>
</ul>
</template>

<script>   
    export default {
        data () {
            return {
                items: [{id: 1, name: 'laptop'}, {id: 2, name: 'keyboard'},{id: 3, name: 'mouse'],
                stockAvailability: {item_1: false, item_2: true, item_3: false}
            }
        },
   computed:{
       fetchItemStatus(){
         return (id)=>this.stockAvailability[`item_${id}`];
       }
     }
    }
</script>

Answer â„–3

If you want to display items with different styles based on their availability, you can create a method to return the correct value:

const app = Vue.createApp({
  data() {
    return {
      items: [{id: 1, name: 'monitor'}, {id: 2, name: 'printer'},{id: 3, name: 'scanner'}],
      outofstock: {item_1: false, item_2: true, item_3: false}
    };
  },
  methods: {
    getOutofstock(id) {
      return this.outofstock[id]
    }
  }
})
app.mount('#demo')
.bg-green-500 {
  color: green;
}
.bg-red-500 {
  color: red;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<ul>
    <li v-for="item in items">
        <div :class="getOutofstock('item_'+item.id) ? 'bg-green-500' : 'bg-red-500' ">
            {{ item.name }}
        </div>
    </li>
</ul>
</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

Tips for establishing a fixed point at which divs cease to shrink as the browser size decreases

There are numerous dynamically designed websites where divs or images shrink as the browser size decreases. A great example of this is http://en.wikipedia.org/wiki/Main_Page The div containing the text shrinks proportionally to the browser size until it ...

What is the process for adding a box shadow beneath my header?

I am currently attempting to add a box shadow under my header, similar to the design featured in the project mockup at https://github.com/RaghavMangrola/the-brighton-times. After trying to implement the following CSS property and value: .header { ...

What is causing the slider image to be the only element that is not adapting to different screen sizes?

I am currently using the flexslider from woothemes and I am unable to understand why the image is consistently wider than the content when the browser window is resized or when viewed on an iPad/iPhone. Upon inspection, I couldn't find any styles on ...

Modifying Row Color in Bootstrap 3: A Step-by-Step Guide

I'm trying to customize the background color of alternating rows in a Bootstrap 3 grid. I attempted to use CSS and add it to the class within the div, but unfortunately, the color isn't changing as expected. Below is the CSS code I used: .row-b ...

Managing input changes in a loop using Vue.js

Can someone verify if the code below is correct, or suggest a better approach? I am trying to handle changes in input values. I have a set of custom options: customOptions: { 1:"test 1", 2:"test 2", 3:"test 3", } These ...

ASP.NET Dynamic Slideshow with Horizontal Reel Scrolling for Stunning

I'm curious if there is anyone who can guide me on creating a fascinating horizontal reel scroll slideshow using asp.net, similar to the one showcased in this mesmerizing link! Check out this Live Demo for a captivating horizontal slide show designed ...

Swapping the icon in the panel heading of Bootstrap 3 Collapse based on its collapse status

Despite many attempts, I haven't been able to make any of the provided answers work in my code. My setup involves using Bootstrap 3 panels and collapse functionality to display advertisements. In the default view, only the advertisement heading is vi ...

Position a Bootstrap 3 division within a central division for ultimate centering

I have written a code snippet that looks like this- html, body, .container-table { height: calc(100% - 50px); } /*Centering a div*/ .container-table { display: table; } .vertical-center-row { display: table-cell; vertical-align: middle; } < ...

VueJS failing to pass parent data to child component

I'm fairly new to Vue Framework and I'm trying to figure out how to update a child component based on changes in the parent component's attributes. In the code snippet below, I've created a component that displays a greeting message bas ...

How can I adjust the brightness, contrast, saturation, and hue in HTML5?

Is there a way to adjust the brightness without turning the image grey? I've been attempting to do so, but only managed to change it to greyscale. My objective is to increase and decrease the brightness of the image. Here is the current code: HTML ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

Is there a way I can turn off the dragging functionality in my situation?

Is there a method to disable the dragging functionality within a draggable element? $('#dragitem').draggable({ scroll : false, drag: function(event, ui){ //check if condition is met if(†...

What is the best way to center my text vertically within a Bootstrap 5 "col" class division?

Struggling to create a Bootstrap 5 page and facing challenges with vertically aligning text in divs? Here's the code snippet causing problems: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

"Concealing specific choices in Autocomplete with reactjs: A step-by-step guide

I am looking for a way to hide the selected option in a Dropdown menu so that it does not appear in the next dropdown. For example, if "Hockey" is selected in the first dropdown, it should not be displayed in the second dropdown; only "Baseball and badmint ...

I prefer not to receive the parent's opacity settings when styling a child element in CSS

Is there a way to prevent the child element from inheriting the opacity of the parent in CSS? I have a parent div and a child div inside it. I want to set the opacity for the parent div, but not have it affect the child div. Does anyone know how I can ac ...

Create a basic Vue.js page using Flask as a single server

There are numerous examples on the internet showcasing applications built with Flask (API) and Vue.js (client). Since Vue is a single-page application (SPA), it makes sense to serve it with Flask as well. However, I have encountered difficulties in finding ...

Ways to create unique hover effects for images in a filter gallery

I recently downloaded a filter gallery from this link and while everything is working fine, I noticed that the hover effect remains the same for all images. The code snippet responsible for this hover effect looks like this: <div class="portfolio"> ...

Bootstrap slider aligned to the right side

I'm currently utilizing bootstrap 3 for my website. However, I encountered an issue with the slider when viewing the page on a mobile device as the image was displaying outside the viewport, shifted to the right. Additionally, in Firefox, the slider ...

The button's unclickability is due to the zIndex being set to -1

How can I create a clickable button? Feel free to check out the sandbox example here: https://codesandbox.io/s/m5w3y76mvy ...

Guidelines for pinpointing local directories

Recently, I obtained a source code for a website navigation that includes a unique set of icons known as "Typicon." The HTML in the source code contains the following: <link rel="stylesheet" type="text/css" href="css/component.css" /> Within the C ...