Reputation: 771
I have some progress bar the width of which are getting from data from the array. The color of this bar depends on the same data. There are 3 colors if progress is 0 the color is grey, more than 0 its blue, and if it 100 its should be green.
<div class="card-item" v-for="item in status" :key="item.id"> // loop
<div class="progress-item">
<span>{{item.progress}}%</span> // data from arr
<div class="progress-bar">
<div class="progress-bar-inner" :style="{width: item.progress}"></div> // width in style should in %
</div>
</div>
</div>
Maybe i should to write the function?
Upvotes: 1
Views: 1566
Reputation: 29071
You can use a method or inline the logic in a style object.
If you only have 3 cases, I would use a conditional class instead of styles, though.
Here's a codepen that shows many possibilities: https://codepen.io/Flamenco/pen/gjNxXp?editors=1111
methods: {
theColor(item){
return item.length===0 ? 'grey' : item.length < 100 ? 'blue' : 'green'}
}
}
<div>using inline style</div>
<div :style="{color: item.length===0 ? 'grey' : item.length < 100 ? 'blue' : 'green'}">...</div>
<div>using method</div>
<div :style="{color: theColor(item)}">...</div>
Using conditional class. Much easier to read, debug, maintain, and extend.
methods: {
theClass(item) {
if (item.length === 0) return 'none'
else if (item.length < 100) return 'under'
else return 'over'
}
}
.none {
color: grey;
}
.under {
color: blue;
}
.over {
color: green;
}
<div>A few ways to do this...</div>
<div :class='theClass(item)'>...</div>
<div :class='[theClass(item), "anotherClass"]'>...</div>
<div :class='{[theClass(item)]:true, anotherClass:true]}'>...</div>
Upvotes: 3