vue实现点击li变色

  • Post author:
  • Post category:vue

利用v-for和v-bind实现点击li变色,由v-for遍历出内容和索引,点击li时传入index,判断遍历的index和点击的currentIndex相等时添加class属性,使其变色

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .active {
      background-color: cadetblue;
    }
  </style>
</head>

<body>
  <div id="app">
    <ul>
      <li v-for='(i,index) in message' @click="btnClick(index)" :class="{active:currentIndex==index}">{{index}}-{{i}}
      </li>
    </ul>
  </div>
  <script src="../js/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        currentIndex: 0,
        message: ['PUBG', 'LOL', 'CF']
      },
      methods: {
        btnClick: function (index) {
          this.currentIndex = index;
        }
      }
    });
  </script>
</body>

</html>

版权声明:本文为qq_56206082原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。