1. 程式人生 > >基於vue的列表圖片選中打鉤

基於vue的列表圖片選中打鉤

首先 css,美化checkbox樣式,這一段程式碼拿過去可以直接用

label {
  font-size: 25px;
  cursor: pointer;
  position: absolute;
  top: -10px;
  right: 0px;
  z-index: 150;
}

label i {
  font-size: 15px;
  font-style: normal;
  display: inline-block;
  width: 18px;
  border-radius: 15px;
  height: 18px;
  text-align: center;
  line-height: 18px;
  color: #fff;
  vertical-align: middle;
  margin: -2px 2px 1px 0px;
  border: #53c7f0 1px solid;
}

input[type="checkbox"],
input[type="radio"] {
  display: none;
  outline: none;
}

input[type="radio"]+i {
  border-radius: 7px;
}

input[type="checkbox"]:checked+i,
input[type="radio"]:checked+i {
  background: #fff;
  color: #53c7f0;
}

接著是內容部分,這裡變數命名比較亂,但是效果都是通過變數控制的,主要思路是點選後,將一個id傳入一個臨時陣列,再遍歷這個臨時陣列,拿陣列中的值與當前值對比,如果對比成功,那麼就讓選中的checkbox顯示出來

相對的,如果想要提交,那麼只需要將臨時陣列傳進去就好了

 <div class="t-recommed-r" v-for="(item,index) in list" :key="index">
        <p><span></span> {{ item.name }} <span></span></p>
        <ul>
          <li v-for="(val,key) in item.data" :key="key" @click="checkTab(val.id)">
            <label v-for="(v, k) in checkedList" :key="k" v-show="val.id === v">
              <input type="checkbox" :checked="val.id === v">
              <i>✓</i>
            </label>
            <a><img src="@/assets/images/null.png"><em>{{ val.name }}</em></a>
          </li>
        </ul>
      </div>

最後一步,js部分

data () {
    return {
      checkedList: [],
      list: []
    }
  },
methods: {
    checkTab (id) {
      let index = this.checkedList.indexOf(id)
      if (index === -1) {
        this.checkedList.push(id)
      } else {
        this.checkedList.splice(index, 1)
      }
  },
}
// 如果存在陣列中,那麼進行刪除操作, 如果不存在,則放入陣列中