1

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.

1
  • You can dynamically bind class like :class="{ 'red-button': name === 'error' }" Commented Jan 27, 2021 at 13:59

3 Answers 3

2

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" >
Sign up to request clarification or add additional context in comments.

Comments

1

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
  }
 }
}

Comments

0

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.

Comments

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.