Joseph
Joseph

Reputation: 873

Vue: Array length conditional in dynamic class

I am cycling through a Firestore collection Colours, and want to use a conditional dynamic class based on the length of array attribute alpha.

I tried:

<v-card v-for="Colour in Colours" :key="Colour.id">
  <v-text-field v-model="Colour.alpha" :value="Colour.alpha" :class="Colour.alpha.length >= '1' ? 'greenClass' : 'blueClass'"></v-text-field>

Which didn't work, and have been searching for an answer, the only relevant suggestion I could find as this:

v-bind:class="{ 'greenClass': Colour.alpha.length >= 1 }"

which also did not work.

Is it possible to use .length like this?

Also, I would like to have multiple conditional classes, eg.

Colour.alpha.length == 0 -> assign class 'white'
Colour.alpha.length == 1 -> assign class 'blue'
Colour.alpha.length == 2 -> assign class 'green'
Colour.alpha.length >= 3 -> assign class 'red'

But I have a feeling this is even less likely to be possible (at least I have no idea how to implement that)

Any suggestions will be greatly appreciated.

Upvotes: 1

Views: 1004

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37883

When binding CSS classes you need to use either object syntax or array syntax

  1. Your 1st example is neither so it doesn't work Passing just a string actually works just fine...
  2. Your 2nd example looks like correct usage of class syntax and should work. Most probable reason it doesn't is Colour.alpha is not always assigned (undefined or null instead of empty array []). So check your data...

const vm = new Vue({
  el: '#app',
  data() {
    return {
      Colours: [
       { id: 1, alpha: [1, 2, 3]},
       { id: 2, alpha: [1, 2]},
       { id: 3, alpha: [1]},
       { id: 4, alpha: []}
      ],
      alphaToClass: ['white', 'blue', 'green', 'red']
    }
  },
  methods: {
    getColorClass(alpha) {
      const index = alpha ? Math.min(alpha.length, 3) : 0
      return this.alphaToClass[index]    
    }
  }
})
.white {
  background-color: white
}

.blue {
  background-color: blue
}

.green {
  background-color: green
}

.red {
  background-color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <div v-for="Colour in Colours" :key="Colour.id">
    <input type="text" v-model="Colour.alpha" :class="getColorClass(Colour.alpha)" />
  </div>
</div>

Upvotes: 1

Related Questions