index.vue 2.88 KB
<template>
  <el-cascader v-model="city" :options="cityList" :props="cascaderProps" :disabled="disabled" @change="onChange"></el-cascader>
</template>
<script>
import cityJson from "@/assets/json/city.json";
export default {
  name: "CitySelect",
  props: {
    value: {
      type: [String, Number],
      default: "",
    },
    checkStrictly: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      cityList: cityJson,
      city: "",
      cascaderProps: {
        value: "code",
        label: "name",
        children: "children",
        checkStrictly: this.checkStrictly,
      },
    };
  },
  watch: {
    value: {
      handler: function (n, o) {
        if (n) {
          this.init();
        }
      },
      immediate: true,
    },
  },
  mounted() {
    //this.city = this.value;
  },
  methods: {
    onChange(e) {
      console.log(e);
      let list = this.cityList;
      let m = list.find((k) => k.code == e[0]);
      let n = m.children.find((k) => k.code == e[1]);
      let b = (n.children || []).find((k) => k.code == e[2]);
      if (n) {
        this.$emit("input", n.name);
      }
      this.$emit("change", { code: e, name: [m.name, n.name, b.name] });
    },

    // 初始化
    init() {
      let o = this.value.toString();
      let list = this.cityList;
      let arr = [];
      if (!o) {
        return false;
      }
      // for(let i =0,len=list.length;i<len;i++){
      //   let k = list[i]
      //   if(k.code == o){
      //     arr.push(k.code)
      //     return false;
      //   }
      // }
      list.forEach((k) => {
        // 只有省份
        if (k.code == o) {
          arr.push(k.code);
          return;
        }
        if (k.children) {
          k.children.forEach((j) => {
            // 只有省市
            if (j.code == o) {
              arr.push(k.code);
              arr.push(j.code);
              return;
            }

            j.children &&
              j.children.forEach((h) => {
                // 只有省市区
                if (h.code == o) {
                  arr.push(k.code);
                  arr.push(j.code);
                  arr.push(h.code);
                  return;
                }
              });
          });
        }
      });
      // let m = list.find((k) => {
      //   let n = k.children.find((j) => j.name == o || j.code == o);
      //   if (n) {
      //     arr.push(k.code);
      //     arr.push(n.code);
      //     return false;
      //   }
      // });
      this.city = arr;
      console.log(arr);
    },

    // 展开数组
    unfoldTree(arr, afterArray = []) {
      let _this = this;
      arr.map((k) => {
        afterArray.push(k);
        if (k.children) {
          _this.unfoldTree(k.children, afterArray);
        }
      });
      return afterArray;
    },
  },
};
</script>
<style lang="scss" scoped>
</style>