vue简单实现 点击变色和隔行变色

简单实现li点击变色,代码如下

<template>
   <div id="app">
            <ul>
               <!--    通过切换索引值改变class -->
               <li v-for="(item,index) in list"
                   :key="index"
                   @click="changeColor(index)"
                   :class="{active:index == num}"
               >{{item}}
               </li>
            </ul>
</template>
<script>
   export default {
      data() {
         return {
            num: 0,
            list: ['000', '111', '222', '333', '444', '555'] //要循环的数组
         }
      },
      methods: {
         changeColor(index) {
            console.log(index)
            this.num = index   //将li的下标赋值给num
         }
      }
   }
</script>
<!--     样式-->
<style lang="scss" scoped>
   #app {
      font-size: 50px;
      text-align: center;
      
      .active {
         background-color: gray;
         color: red;
      }
   }
</style>

简单实现点击隔行变色,代码如下

<template>
   <div id="app">
      <!--    利用v-for中的index值,绑定样式来实现隔行变色效果 -->
      <ul>
         <!--     键值对 判断条件  -->
         <li v-for="(item,index) in list"
             :key="index"
             @click="changeColor(index)"
             :class="{on:index==num&&index%2==0,off:index==num&&index%2!=0}"
         >{{item}}
         </li>
      </ul>

      <ul>
         <!--      三元运算符写法  -->
         <li v-for="(item,index) in list"
             :key="index"
             @click="changeColor(index)"
             :class="num==index&&index%2 ==0?'on':''||num==index&&index%2 !=0?'off':''"
         >{{item}}
         </li>
      </ul>
   </div>
</template>
<script>
   export default {
      data() {
         return {
            num: 0,
            list: ['000', '111', '222', '333', '444', '555'] //要循环的数组
         }
      },
      methods: {
         changeColor(index) {
            console.log(index)
            this.num = index   //将li的下标赋值给num
         }
      }
   }
</script>
<!--     样式-->
<style lang="scss" scoped>
   #app {
      font-size: 50px;
      text-align: center;

      .on {
         background: gray;
         border: 2px solid red;
      }

      .off {
         background: indigo;
         border: 2px solid blue;
      }
   }

</style>
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值