Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

vue.js - 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.

question from:https://stackoverflow.com/questions/65920602/looping-in-vue-and-adding-dynamic-classname

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...