利用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>
Logo

前往低代码交流专区

更多推荐