Vue实现多选功能

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

<head>
  <meta charset="UTF-8">
  <meta>
  <title>Document</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <style type="text/css">
    * {
      margin: 0;
      padding: 0;
    }

    .box {
      width: 100%;
      height: 30px;
      line-height: 30px;
      margin: 150px 150px;
    }

    .box li {
      width: 152px;
      height: 30px;
      line-height: 30px;
      display: inline-block;
      text-align: center;
      cursor: pointer;
      list-style: none;
      margin-left: 5px;
      background-image: linear-gradient(0deg,
          #dbbc8e 0%,
          #f9e0be 52%,
          #ebcfa9 100%),
        linear-gradient(#ebbd82,
          #ebbd82);
      background-blend-mode: normal,
        normal;
      border: solid 1px #ffb559;
      font-size: 16px;
      font-weight: 700;
      letter-spacing: 3px;
      color: #754306;
    }

    .box li .checkbox {
      width: 18px;
      height: 18px;
      content: "";
      margin-right: 2px;
      margin-top: -3px;
      display: inline-block;
      /*一定要将div设置为inline-block*/
      vertical-align: middle;
      /*设置该元素在父元素中的位置*/
      background: url('./img_p1.png') no-repeat;
      background-size: 100% 100%;
    }

    .box li.checked .checkbox {
      background: url('./img_p2.png') no-repeat;
      background-size: 100% 100%;
    }
  </style>
</head>

<body>
  <div id="app">
    <div class="box">
      <ul>
        <li v-for="item,index of cities" :class="{checked:item.check}" @click="checkChange(index,item.city)">
          <div class="checkbox"></div>
          {{item.city}}
        </li>
      </ul>
      选择了:{{choose}}
    </div>
  </div>
  <script>
    var app = new Vue({
      el: "#app",
      data: {
        cities: [{
            city: "中国",
            check: false
          },
          {
            city: "滑动",
            check: false
          },
          {
            city: "重庆",
            check: false
          },
          {
            city: "广州",
            check: false
          },
          {
            city: "西安",
            check: false
          }
        ],
        choose: []
      },
      methods: {
        checkChange(index, name) {
          let that = this;
          that.cities[index].check = !that.cities[index].check;
          if (that.cities[index].check == true) {
            that.choose.push(that.cities[index].city);
          } else {
            let indexes = that.choose.indexOf(name);
            that.choose.splice(indexes, 1);
          }
          console.log(that.choose);
        }
      }
    })
  </script>
</body>

</html>

  

posted @ 2021-04-28 13:16  全村最靓的程序猿  阅读(1366)  评论(0编辑  收藏  举报