数据字典2


<template>
  <div class="SelectDataCode">
    <div v-if="readOnly">
      {{ labelName }}
    </div>
    <el-select v-model="value" v-else v-bind="$attrs" v-on="$listeners">
      <el-option
        v-for="item in options"
        :key="item[defaultProps.value]"
        :label="item[defaultProps.label]"
        :value="item[defaultProps.value]"
      ></el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'SelectDataCode',
  data() {
    return {
      value: '',
    }
  },
  props: {
    readOnly: {
      //用于只读显示
      type: Boolean,
      default: false,
    },
    dataCode: {
      type: String,
      required: true,
    },
    dataCodeValue: {
      type: Number | String,
      required: true,
    },
    defaultProps: {
      type: Object,
      default: () => {
        return {
          label: 'name',
          value: 'code',
        }
      },
    },
  },
  computed: {
    options() {
      let dataCodes = this.$store.getters['dataCode/dataCodes']
      return dataCodes[this.dataCode] || [];
    },
    labelName() {
      if (this.readOnly && this.value && this.options) {
        if (this.$attrs.hasOwnProperty('multiple')) {
          //多选
          let arr = this.value.split(',')
          return arr
            .map((item) => {
              return this.findOne(item)
            })
            .join(';')
        } else {
          return this.findOne(this.value)
        }
      } else {
        return ''
      }
    },
  },
  watch: {
    dataCodeValue: {
      handler: function (oldval, newval) {
        this.value = this.dataCodeValue
      },
      immediate: true,
    },
    value: {
      handler: function (oldval, newval) {
        this.$emit('update:dataCodeValue', this.value)
      },
    },
  },
  methods: {
    findOne(value) {
      return this.options.find((item) => {
        return item[this.defaultProps.value] === value
      })[this.defaultProps.label]
    },
    clearValue() {
      this.$emit('update:dataCodeValue', '')
    },
  },
}
</script>
<style  scoped></style>