Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create method and return right 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading