tinti
tinti

Reputation: 1475

Looping in Vue and adding dynamic className

I am quite new to Vue and I have an issue. I have an array of objects and I want the wrapper of the loop to have dynamic className For example

<div v-for="({time, date, name}, i) in myObject" :key="i" class="my-custom-class">

well, if the key (i) is greater than 3 then I want the className to have a different name or at least to add an extra name (like hiddenDiv).

I know is not possible to add the v-if condition in the v-for statement. Any help is appreciated.

Upvotes: 1

Views: 2289

Answers (3)

Yash Maheshwari
Yash Maheshwari

Reputation: 2412

If you want to apply a dynamic class in vue then you can use class bindings to apply a specific class to the element.

You can read about class and style bindings here.

Also, you can define a method with the class and apply some conditions on which the class needs to be changed.

Upvotes: 0

Amaarockz
Amaarockz

Reputation: 4674

Another way of doing this using computed property...

<div v-for="({time, date, name}, i) in myObject"
:key="i" :class="getClassName(i)" class="my-custom-class" >

and in your computed

computed: {

 getClassName() {
  return i => {
     if(i === 0) return 'classOne';
     elseif(i === 1) return 'classTwo'
     else return 'classThree';
    // In this way you can maintain as many classNames you want based on the condition
  }
 }
}

Upvotes: 1

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You could bind the class using a condition based on the current loop index :class="{'hide-div':i>3}":

<div v-for="({time, date, name}, i) in myObject"
:key="i" :class="{'hide-div':i>3}" class="my-custom-class" >

Upvotes: 2

Related Questions