Elkazi
Elkazi

Reputation: 177

How to add conditions with VUE for classes

it's possible to make conditions with Vue to change add class according to the text loaded on the doom?

I have a list with colors name

<span>yellow</span>
<span>red</span>
<span>grey</span>

I want to make a condition for example if the name text is yellow I want to add class "color_yellow" and so on

Upvotes: 2

Views: 204

Answers (2)

shafikshaon
shafikshaon

Reputation: 6404

You may try this

<span :class="color.colorName">{{ color.colorName }}</span>

In css,

.yellow { color: yellow }
.red { color: red }

For more details, you can check https://v2.vuejs.org/v2/guide/class-and-style.html

Upvotes: 0

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23480

Try like following snippet:

new Vue({
  el: '#demo',
  data() {
    return {
      colors: ['yellow', 'red', 'grey']
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
.color_yellow {
  color: yellow;
}
.color_red {
  color: red;
}
.color_grey {
  color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <ul>
    <li v-for="(color, i) in colors" :key="i">
      <span :class="`color_${color}`">{{ color }}</span>
    </li>
</div>

Upvotes: 2

Related Questions