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

The loading feature of jQuery UI Autocomplete - .ui-autocomplete-loading is ingenious

When fetching the XML file for the search box, I would like to apply this css. It currently takes around 3 seconds to load the file. In the autocomplete.js file, I found these two functions: _search: function( value ) { this.term = this.element ...

How can I ensure that Div and its contents are only responsive to changes in width?

Initially, I'm feeling a bit confused but I'll try my best to articulate my issue and what I need. Within a div element, there's another div that I want to move left and right only, following the same path as an image when resizing (refer t ...

What do you do when you need to hide a table column that has a colspan

I have been searching for a solution to my unique table structure, but I haven't found any that match my situation. When attempting to hide column A or B, the following code works perfectly: $('table td:nth-child(1),table th:nth-child(1)') ...

What is the best method to eliminate the 2px flaws on the right edge?

Issue only observed on small screens using Android Chrome (Nexus 5x, Nexus 6) with Android 5+. Cannot replicate problem on a Nexus 4. Utilizing basic bootstrap setup and angular; unsure if related. Experiencing artifacts up to 2px wide on the right side o ...

How to effectively use flexbox to resize child elements in a CSS layout

My goal is to create a layout where a child element fills the entire flex box of a flex layout. Here is an example of the HTML structure I am using: <div class="parent"> <div class="child1"> should have 100px height </div&g ...

Get rid of the background shade in the area separating the menu items within a CSS menu

Is there a way to add some spacing between the menu items without affecting the background color applied to the anchor tags? I currently use a right margin of 13px for the spacing, but it also applies the background color, which is not the desired outcome ...

How should the directory be organized for the param with a prefix in Nuxt.js?

My route is set up as /en/rent-:productSlug How should I organize the directory for this route, considering that the parameter productSlug includes the prefix rent? ...

establishing irregular edges for the div container

Looking to create a class that can transform an element into a specific shape using CSS. Not entirely sure if this is achievable with pure CSS alone, but applying a class to the image element will morph it into the desired shape as shown below. <style ...

Enhancing JEST testing efficiency using vue.js

I am currently working on a basic app with a few components and only one test for the Login.vue component. Whenever I run jest, it seems to take around 10 to 20 seconds each time. I was wondering if there are any ways to improve the performance or if this ...

Rendering Content Conditionally Using Vue and Prime Vue Component Library

Currently, I have a diagram that consists of inputs and outputs. With the help of Primevue, I am able to render a table with data for either the inputs or outputs individually. However, I need the columns in the table to vary depending on whether it is dis ...

Connecting a custom bootstrap stylesheet to WordPress

I'm having trouble linking my WordPress Stylesheet to a child theme in a different directory/subfolder. The code I placed in the functions.php file doesn't seem to be working correctly. Here is the code snippet: function theme_add_bootstrap() { ...

CSS for mobile devices not loading until the device is rotated

My website, redkrypt.com, is functioning perfectly on my laptop. However, I am facing an issue where the css file will only load on my iPhone 4S after I rotate it once. Once I do this, the website works both vertically and horizontally. I have tried variou ...

Flexbox can be incorporated with a slide down animation to create

Currently I am attempting to replicate the "slideUp" and "slideDown" features in jQuery while utilizing a flexbox for display! jQuery.fn.toggleFlexbox = function() { var elm = $(this[0]); if(elm.css('display') === "none"){ elm.cs ...

Using asynchronous import statements in Vue allows for more efficient loading of components

I am using Vue and have a method in my file called load.js. async function loadTask(x) { return await x; // Some async code } export { loadTask }; In one of my Vue components, I call the method but encounter an issue where the use of await prevents the ...

Utilizing CSS to Display a Variety of Colors within a Text String

Is it possible to style different words in a sentence with various colors using only CSS, without using the span element? For instance, how can I make the word "Red" appear in red, "Blue" in blue, and "Green" in green within an h1 tag? ...

Interactive YouTube Video Player that keeps video playing in original spot upon clicking the button

Currently, I'm working on a project that involves combining navigation and a video player within the same div container. Here is an image link And another image link The concept is that when you click on one of the four boxes, a new video will appe ...

Vue.js 3 with TypeScript is throwing an error: "Module 'xxxxxx' cannot be located, or its corresponding type declarations are missing."

I developed a pagination plugin using Vue JS 2, but encountered an error when trying to integrate it into a project that uses Vue 3 with TypeScript. The error message displayed is 'Cannot find module 'l-pagination' or its corresponding type ...

Troubleshooting Vue computed property access issues

Currently, I am in the early stages of learning Vue and have moved on to exploring validation. While looking at some older examples that utilize Vee-Validate, it seems that there has been recent changes to the library. How can I update this code to work w ...

The anchor tag seems to be malfunctioning within the div container

<style type="text/css> .xyz { position: absolute; top: 120px; left: 160px; z-index: -1; } #container { position: relative; overflow: visible; opacity: .3; } </style> <body> <div> <video i ...

Is it possible to view the CSS of a PDF file in print template mode using Chrome?

https://i.stack.imgur.com/XlcWm.png Currently facing an issue with debugging CSS on my PDF template. I am unable to inspect the styles directly in the CSS due to limitations. When using inspect element in Chrome, only the styles for text and elements are ...