index.vue 1.69 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;
      let list = this.cityList;
      let arr = [];
      if (!o) {
        return false;
      }
      let m = list.find((k) => {
        let n = k.children.find((j) => j.name == o);
        if (n) {
          arr.push(k.code);
          arr.push(n.code);
        }
      });
      this.city = arr;
      console.log(arr);
    },
  },
};
</script>
<style lang="scss" scoped>
</style>