css 给多种状态的盒子赋予不同样式

开发时经常会遇到这样的样式需求:【根据返回的字段控制当前盒子使用不同的样式】

一般来说,字段内容都为两种:true/false,或0/1,或两个不同的字符串,这种情况下可以使用【动态class+三元表达式】的方法解决。

但偶然也会出现多个的情况,此时三元表达式就显得不够用了,要么会判断很多层变得冗长,要么彻底不适用,所以遇到这种情况应该如何解决呢?

——其实很简单,只需要借助模板字符串就可以解决了。

 

举个例子:

当前盒子共有四种状态,延期为红色,完成为绿色,未开始为灰色,进行中为黄色。

<div :class="`${item.color}`"v-for="(item, index) in list[i].child" :key="index" @click="showLog(item, i)">
  <p class="ppp">
    {{ item.name }}
  </p>
</div>
list: [
  { 'id': 1, child: [{ name: '111', color: 'green' }] },
  { 'id': 2, child: [{ name: '221', color: 'red' }] },
  { 'id': 3, child: [{ name: '331', color: 'green'}, { name: '332', color: 'red' }] },
  { 'id': 4, child: [{ name: '441, color: 'yellow' }, { name: '442', color: 'yellow' }] },
  { 'id': 5, child: [{ name: '551', color: 'gray' }] },
  { 'id': 6, child: [{ name: '661', color: 'gray' }] },
]
.gray,
.green,
.red,
.yellow
 {
  padding: 8px;
  margin: 5px 0;
  height: 70px;
  color: #fff;
  font-size: 12px;
  border-radius: 5px;
}

.gray {
  background-color: rgb(177, 175, 175);
}

.green {
  background-color: rgb(78, 201, 91);
}

.red {
  background-color: rgba(214, 54, 54, 0.958);
}

.yellow {
  background-color: rgba(253, 253, 93);
}

(图与代码并不对应,懒得写样例了,意思一下)

 

posted @ 2023-06-14 18:08  沐夏52Hz  阅读(124)  评论(0)    收藏  举报