Skip to content
Advertisement

Vue.js, options for multiple classes on v-bind

I need some help trying to figure out how to give the v-bind:class multiple options.

My Uno game, as it loops through your cards, needs to look at the cards color which is in a list of objects ex. ([{ Color: green, Value: 6}] and determine what color of text the card should be.

This is what I have come up with so far:

Vue.js

getClass: function(card){
            var result = [];
            console.log(card);
            if (card.Color == "red"){
                result.push('red');
            }else if (card.Color == "green"){
                result.push('green');
            }else if (card.Color == "blue"){
                result.push('blue');
            }else if(card.Color == "yellow"){
                result.push('yellow');
            }
            console.log(result);
            return result;
        },

HTML

<ul id="myCards">
        <button id="myCard" v-for="card in myCards" v-bind:class="getClass(card)" 
         @click="playCard(card)">
         {{card.Color}} {{card.Value}}
        </button>
</ul>

CSS

ul{
    text-align: left;
}
#myCards{
    padding: none;
}
#myCard{
    display: inline-block;
    height: 100px;
    width: 70px;
    border: 1px solid black;
    color: black;
    border: 2px solid black;
    border-radius: 6px;
    background-color: white;
    color: black;
    vertical-align: middle;
    margin: 5px;
}
.red{
    color: red;
}
.green{
    color: green;
}
.blue{
    color: blue;
}
.yellow{
    color: yellow;
}

Advertisement

Answer

Since there’s one property called Color inside the card object you could use style object syntax and you don’t need to define classes for each color:

<ul id="myCards">
        <button id="myCard" v-for="card in myCards" 
         @click="playCard(card)">
         {{card.Color}} {{card.Value}}
        </button>
</ul>

Vue.config.devtools = false;
Vue.config.productionTip = false;

let app = new Vue({
  el: "#app",

  data() {
    return {
      myCards: [{
          Value: 'card 1',
          Color: 'red'
        },
        {
          Value: 'card 2',
          Color: 'blue'
        },
      ]

    }
  },
  methods: {


  }
})
ul {
  text-align: left;
}

#myCards {
  padding: none;
}

#myCard {
  display: inline-block;
  height: 100px;
  width: 70px;
  border: 1px solid black;
  color: black;
  border: 2px solid black;
  border-radius: 6px;
  background-color: white;
  color: black;
  vertical-align: middle;
  margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul id="myCards">
    <button id="myCard" v-for="card in myCards" :style="{color:card.Color}">
         {{card.Value}}
        </button>
  </ul>
</div>
Advertisement