Vue v-for实现不同元素添加不同样式

使用二元或三元运算符对类名进行动态赋值,不同类名设置不同样式

关键代码(三种写法都可以)

二元用 { }

:class="{‘red’:index=1,‘blue’:index=2}"

三元用 [ ]

:class="[index=0?‘red’:’’,index=1?‘blue’:’’]"

:class="[index===0?‘red’:‘blue’]"

<template>
  <div style="margin:100px">
    <ul>
      <li v-for="item in list"
          :class="[index===0?'red':'',index===1?'blue':'']">   // 类名动态赋值
          // :class="{'red':index===1,'blue':index===2}"
          //:class="[index===0?'red':'blue']"
        {
    
    {
    
    item}}
      </li>
    </ul>
  </div>
</template>
<script>
export default {
    
    
  data () {
    
    
    return {
    
    
      list: ['jack', 'Anna', 'Lily', 'Tom']
    }
  },
</script>
<style lang="scss">
ul {
    
    
  li {
    
    
    &.red {
    
                  // 不同类名添加不同样式
      color: red;
    }
    &.blue {
    
    
      color: blue;
    }
  }
}
</style>

效果图
效果图

猜你喜欢

转载自blog.csdn.net/weixin_42164004/article/details/108752640