1

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.

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

sorry, human error on this one, I was editing code for one section of my work and expecting changes in another section. Totally my mistake! The 1st example does actually seem to be working now on my code. Thank you for you reply
Thank you very much @Michal! Your edit with the getColorClass() works perfectly. I didn't even think to use a method like that to determine class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.