从数组Vue动态添加样式

时间:2018-08-16 12:24:43

标签: vue.js vuejs2

我有一些进度条,其宽度是从数组数据中获取的。该条的颜色取决于相同的数据。如果进度为0​​,则有3种颜色,灰色为灰色,蓝色为0以上,如果为100,则为绿色。

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

也许我应该编写函数?

1 个答案:

答案 0 :(得分:1)

您可以使用方法或在样式对象中内联逻辑。

如果只有3种情况,我会使用条件类而不是样式。

下面是一个显示许多可能性的codepen: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>

使用条件类。易于阅读,调试,维护和扩展。

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>

相关问题