LocationSelect.vue 2.28 KB
Newer Older
wanli's avatar
wanli committed
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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
<template>
  <el-cascader
    v-if="visible"
    :props="props"
    :placeholder="placeholder"
    v-model="value"
    :clearable="clearable"
    @change="$emit('change')"
    @input="handleInput"
  ></el-cascader>
</template>

<script>
import { fetchByParentId } from '@/api/system/location'

export default {
  name: 'LocationSelect',
  props: {
    placeholder: {
      default: '请选择地区'
    },
    level: {
      default: 3
    },
    clearable: {
      default: false
    },
    // 省
    provinceId: {},
    // 市
    cityId: {},
    // 区
    areaId: {}
  },
  data () {
    const vm = this
    return {
      // 是否展示,用于重新初始化cascader
      visible: true,
      // 已选值
      value: [],
      // 组件配置
      props: {
        lazy: true,
        lazyLoad (node, resolve) {
          const { level } = node
          fetchByParentId(level === 0 ? -1 : node.value)
            .cache()
            .then(data => {
              resolve(data.map(item => {
                return {
                  label: item.name,
                  value: item.id,
                  leaf: level >= vm.level - 1
                }
              }))
            })
            .catch(e => {
              vm.$tip.apiFailed(e)
            })
        }
      }
    }
  },
  watch: {
    provinceId (newValue) {
      this.value[0] = newValue
      if (this.level === 1) {
        if (newValue == null) {
          this.value = []
        }
        this.__rebuild()
      }
    },
    cityId (newValue) {
      if (this.level >= 2) {
        this.value[1] = newValue
      }
      if (this.level === 2) {
        if (newValue == null) {
          this.value = []
        }
        this.__rebuild()
      }
    },
    areaId (newValue) {
      if (this.level >= 3) {
        this.value[2] = newValue
      }
      if (this.level === 3) {
        if (newValue == null) {
          this.value = []
        }
        this.__rebuild()
      }
    }
  },
  methods: {
    handleInput (values) {
      this.$emit('update:province-id', values[0])
      this.$emit('update:city-id', values[1])
      this.$emit('update:area-id', values[2])
    },
    // 重新初始化cascader
    __rebuild () {
      this.visible = false
      this.$nextTick(() => {
        this.visible = true
      })
    }
  }
}
</script>