Vue自定义复选框checkbox样式

隐藏自身,并借助label标签和for属性,伪造选中状态

<template>
  <div class="service-list">
    <div
      class="checkbox-item"
      v-for="item of serviceList"
      :key="item.id"
    >
      <input
        v-if="isShowCheckbox"
        type="checkbox"
        :id="item.id"
        :value="item.id"
        v-model="checkedNames"
      >
      <label
        :for="item.id"
        class="checkbox-default"
        v-bind:class="checkedNames.includes(item.id)?'checkboxActive':''"
        @click="selectNames(item.id)"
  >
{{item.title}}
      </label>
    </div>
  </div>

    {{checkedNames}}
</template>

<script>
export default {
  name: 'Test',
  data () {
    return {
      isShowCheckbox: false,
      checkedNames: [],
      serviceList: [{
        id: '0001',
        title: '洗护'
      }, {
        id: '0002',
        title: '剪发'
      }, {
        id: '0003',
        title: '烫发'
      }, {
        id: '0004',
        title: '染发'
      }, {
        id: '0005',
        title: '接发'
      }, {
        id: '0006',
        title: '服务5'
      }, {
        id: '0007',
        title: '服务5'
      }, {
        id: '0008',
        title: '服务8'
      }, {
        id: '0009',
        title: '服务8'
      }, {
        id: '0010',
        title: '服务8'
      }, {
        id: '0011',
        title: '服务8'
      }]
    }
  },
  methods: {
    selectNames (e) {
      if (this.checkedNames.includes(e)) {
        this.checkedNames.splice(this.checkedNames.indexOf(e), 1)
      } else {
        this.checkedNames.push(e)
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.service-list {
  width: 100%;
  margin-top: 0.1rem;
  margin-bottom: 0.44rem;
  display: flex;
  flex-wrap: wrap;
}

.checkbox-item {
  width: calc((96% / 3));
  height: 0.7rem;
  margin-left: 0.07rem;
  margin-top: 0.1rem;
}

.checkbox-default {
  width: 100%;
  height: 0.7rem;
  line-height: 0.7rem;
  float: left;
  text-align: center;
  background-color: rgb(255, 245, 249);
  border-radius: 0.4rem;
}

.checkboxActive {
  width: 100%;
  height: 0.7rem;
  line-height: 0.7rem;
  float: left;
  text-align: center;
  background-color: rgb(254, 79, 113);
  border-radius: 0.4rem;
  color: #FFF;
}
</style>

页面效果

请输入图片描述

Last modification:April 23rd, 2019 at 08:48 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment