SoFunction
Updated on 2025-02-28

Use index value in v-for to achieve interlaced color change

First, define the style, use the index value in v-for, and then bind the style to achieve the interlaced color change effect.

The following is the complete code, which is very simple, but also a trick.

<!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>title</title>
  <style>
    .on {
      background: red;
      border: 1px solid blue;
    }
    .off {
      background: yellow;
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <div >
    <ul>
<!--usev-forIn-houseindexvalue,Bind styles to achieve interlaced color change effect-->
      <li v-for="(name,index) in names" :class="{on:index%2==0,off:index%2!=0}">{{name}}</li>
    </ul>
  </div>
  <script src="./"></script>
  <script>
    var vm = new Vue({
      el: "#app",
      data: {
        names: ['000', '111', '222', '333', '444', '555']
      }
    });
  </script>
</body>
</html>

Summarize

The above is what the editor introduced to you. Using the index value in v-for to achieve interlaced color changes, I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!