Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js dynamic class variable in variable

I want to ask you, if its possible doing this with dynamic class like this. <div :class="'outofstock.item_' + item.id ? 'bg-green-500' : 'bg-red-500' "> If exist solution, I cant find a rigth syntax for this. Thank you for a answers.

thats a example what I try to do. I need a result outofstock.item_1, outofstock.item_2 and outofstock.item_3 in :claas

<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>
like image 403
StEvE Avatar asked Sep 26 '26 21:09

StEvE


2 Answers

This works without calling a method: Vue Playground

<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>
like image 77
tauzN Avatar answered Sep 28 '26 21:09

tauzN


Define a computed property that returns a function which takes the item id as parameter, then use string template `` to render the right class :

<template>
<ul>
    <li v-for="item in items">
        <div :class="`${getItemValue(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}
            }
        },
   computed:{
       getItemValue(){
         return (id)=>this.outofstock[`item_${id}`];
       }
     }
    }
</script>

like image 45
Boussadjra Brahim Avatar answered Sep 28 '26 21:09

Boussadjra Brahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!