1

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?

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome answer! Just to note: your second example in your last code snippet, you should be using double quotes somewhere otherwise you'll get a syntax error in your markup :)
Great solution! Can you help me with width? The width of the progress bar should be in %, as it has position absolute and has to fill its parent due to progress value. I have tried width: item.progress, but its set the width only if the value is 0. Have any ideas?
@SashaZoria Try these: width: item.progress + '%' or width: ${item.progress}% <- stackoverflow is replacing my backticks...

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.