checker.vue 1.9 KB
Newer Older
C
christlala 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
<template>
  <ul class="cube-checker">
    <slot>
      <cube-checker-item
        v-for="(option, index) in options"
        :option="option"
        :key="index" />
    </slot>
  </ul>
</template>
<script type="text/ecmascript-6">
  import CubeCheckerItem from './checker-item.vue'
  const COMPONENT_NAME = 'cube-checker'
  const EVENT_INPUT = 'input'

  export default {
    name: COMPONENT_NAME,
    props: {
      value: [String, Number, Array],
      options: {
        type: Array,
        default() {
          /* istanbul ignore next */
          return []
        }
      },
      type: {
        type: String,
        default: 'checkbox'
      },
      min: {
        type: Number,
        default: 0
      },
      max: {
        type: Number,
        default() {
          return this.options.length
        }
      }
    },
    data () {
      return {
        currentValue: this.value
      }
    },
    computed: {
      isRadio() {
        return this.type === 'radio'
      }
    },
    watch: {
      value (newValue) {
        this.currentValue = newValue
      },
      currentValue (val) {
        this.$emit(EVENT_INPUT, val)
      }
    },
    methods: {
      check(option) {
        if (this.isRadio) {
          this.checkRadio(option)
        } else {
          this.checkCheckbox(option)
        }
      },
      checkRadio(option) {
        this.currentValue = option.value
      },
      checkCheckbox(option) {
        const value = option.value
        const currentValue = this.currentValue
        const valueLen = currentValue.length
        const min = this.min
        const max = this.max

        const index = currentValue.indexOf(value)

        if (index > -1) {
          (valueLen > min) && currentValue.splice(index, 1)
        } else {
          (valueLen < max) && currentValue.push(value)
        }
      }
    },
    components: {
      CubeCheckerItem
    }
  }
</script>