P1_10
P1_10

Reputation: 113

How to conditionally apply CSS class in a VueJs object iteration?

Code in Vuetify:

<v-layout row wrap> 
     <v-flex xs2 v-for="(month, key) in months" :key ="key">
          <router-link class = "decoration" :to="month.target">{{(month.month)}}</router-link>
     </v-flex> 

The "v-for" is iterating through an array of objects, which have different properties:

data () {
    return {

        months: [
           {
               month: 'Gen',
               target: ''
           },
           {
               month: 'Feb',
               target: ''
           },
          and so on.

How can I conditionally apply the class underlined in the first code block, so that can underline only some months and not all of them?

Thank you in advance!

Upvotes: 1

Views: 5002

Answers (4)

kaizer_bun
kaizer_bun

Reputation: 49

I believe you can do something like this:

<router-link :class="{'underlined': month.shouldUnderline}" :to="month.target">{{(month.month)}}</router-link>

Let me know if that works!

Edit: more info here (also mentions multiple classes): https://v2.vuejs.org/v2/guide/class-and-style.html

Upvotes: 0

Chi
Chi

Reputation: 308

You can do it like this:

<td :class="props.item[3] == 'pawned' ? 'text-red' : ''">{{ props.item[2] }}</td>

Upvotes: 0

Marina Mosti
Marina Mosti

Reputation: 461

While both the other answers are correct, if i understood correctly you want both classes - the fixed and a dynamic one.

You can achieve this by doing:

<router-link class="decoration" :class="{ underlined: CONDITION }" :to="month.target">{{(month.month)}}</router-link>

You can easily set this condition on a method:

methods: {
   isUnderlined() { return SOME IF STATMENT OR SOMETHING }
}

Do not wrap the :class with brackets [] like the other answer states, as it expects an object {}

Upvotes: 0

trk
trk

Reputation: 2228

Just use :class = '[{"className": X}]'. Note the : immediately before the class attribute.

where, X is a computed / data property in the vue component that is Boolean. True will add the class and False won't.
className is your css classname.

Upvotes: 3

Related Questions