select-category.vue 1.57 KB
<template>
  <Cascader :data="categoryList" :value="handleValue" change-on-select @on-change="selectChange"></Cascader>
</template>

<script>
import ApiService from "service/api";

export default {
  props: {
    value: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    let self = this;
    return {
      handleValue: self.value.map(i => i.value),
      categoryList: []
    };
  },
  created() {
    this.api = new ApiService();
    this.getSortList();
  },
  methods: {
    getSortList() {
      this.api.getSortList().then(result => {
        this.categoryList = result.list.map(i => {
          let sortItem = {
            value: i.id,
            label: i.sortName
          };

          if (i.subList) {
            sortItem.children = i.subList.map(s => {
              return {
                value: s.id,
                label: s.sortName
              };
            });
          }

          return sortItem;
        });
      });
    },
    selectChange(val) {
      const len = val.length;

      const max = val[0] || "";
      const mid = val[1] || "";

      let maxItem = this.categoryList.find(i => i.value == max) || {};
      let midItem =
        (maxItem &&
          maxItem.children &&
          maxItem.children.find(i => i.value == mid)) ||
        {};

      this.$emit("input", [
        { value: max, label: maxItem.label || "" },
        { value: mid, label: midItem.label || "" }
      ]);
    }
  },
  watch: {
    value(newValue) {
      this.handleValue = newValue.map(v => v.value);
    }
  }
};
</script>

<style>

</style>