checkbox-size.vue 2.91 KB
<template>
    <Checkbox-group :value="updateValue" @on-change="selectSize">
        <Checkbox v-for="size in sizes" :key="size.id" :label="size.id" :disabled="size.disabled">
            <span>{{size.sizeName}}</span>
        </Checkbox>
    </Checkbox-group>
</template>

<script>
import _ from 'lodash';
import SizeService from 'services/product/size-service';

export default {
    name: 'checkbox-size',
    props: {
        sortId: {
            type: [Number, String]
        },
        selectSizes: {
            type: Array,
            default() {
                return [];
            }
        },
        value: {
            type: Array,
            default() {
                return [];
            }
        }
    },
    created() {
        this.sizeService = new SizeService();
        this.render();
    },
    data() {
        let _this = this;

        return {
            sizes: [],
            updateValue: _.concat(_.map(_this.selectSizes, size => {
                return size.id;
            }), _.concat(_.map(_this.value, size => {
                return size.id;
            })))
        };
    },
    methods: {
        render() {
            this.sizeService.getSize(this.sortId).then((result) => {
                this.initSizes(result.data);
            });
        },
        initSizes(sizes) {
            this.sizes = sizes.map(size => {
                let selectColor = _.find(this.selectSizes, c => c.id === size.id);

                if (selectColor) {
                    size.disabled = selectColor.disabled;
                    size.selected = true;
                } else {
                    size.disabled = false;
                    size.selected = false;
                }
                return size;
            });
        },
        selectSize(values) {
            let newSize = this.sizes.filter(size => _.some(values, val => val === size.id));

            let oldSize = this.sizes.filter(size => size.selected);

            this.sizes.forEach((size) => {
                size.selected = false;
            });
            newSize.forEach((size) => {
                size.selected = true;
            });

            let addSize = _.differenceWith(newSize, oldSize, function(left, right) {
                return left.id === right.id;
            });

            let removeSize = _.differenceWith(oldSize, newSize, function(left, right) {
                return left.id === right.id;
            });

            this.$emit('on-change', newSize);
            this.$emit('input', newSize);

            // 差别数据
            if (!_.isEmpty(addSize)) {
                this.$emit('on-add', addSize);
            }

            if (!_.isEmpty(removeSize)) {
                this.$emit('on-remove', removeSize);
            }
        }
    },
    watch: {
        value(newValue) {
            this.updateValue = _.map(newValue, size => {
                return size.id;
            });
        }
    }
};

</script>