vue中如何根据元素的值,判断去绑定不同的样式?

clipboard.png

如何根据每一个组别判断,下面button显示不同的颜色?比如 双排键组下面的显示红色,电钢琴组显示黑色。。。。

clipboard.png

阅读 10.8k
8 个回答

初始化一下items,对你需要的item设置相应的class,不用统一都使用playPar样式。

<span :class="item.TypeGroupName==='电钢琴'? '黑色样式': ">
<span :class="item.TypeGroupName==='双排键'? '红色样式': ">

就根据你li循环的每一项item来判断啊,用v-class或者v-style
比如,在div上绑定 class = {'red':item.name == "双排键",'green':item.name == "电子琴"},
然后在css中定义这两个类;

item加个id,比如0,1,2
<span :class="item.id===0? 'a': ''>
<span :class="item.id===1? 'b': ''>
这样后期如果item.TypeGroupName变了也没关系

笨办法
<ul id="app">

<li v-for="x in list" :style="{color:listcolor[x]}">111111111</li>

</ul>
<script type="text/javascript">

    var vm = new Vue({
  el: '#app',
  data: {
      list:[1,2,3,4],
      listcolor:{"1":"red",
      "2":"blue",
      "3":"green",
      "4":"yellow"
  }
  }
})

</script>

例如:

<div v-bind:style="styleObject"></div>
data: {
  styleObject: {
    color: 'red',
    fontSize: '13px'
  }
}

参照 vue 文档:class 和 styles 绑定

加类名。或者data-属性。

直接用css可以吗?

  .listItem:nth-child(1) .playPar {
             background-color: #f00;
         }
        .listItem:nth-child(2) .playPar {
            background-color: #000;
        }
        .listItem:nth-child(3) .playPar {
            background-color: #0f0;
        }
        .listItem:nth-child(4) .playPar {
            background-color: #0ff;
        }

或者
<li v-for="(item, index) in items">
根据index来设置样式

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题