SelectZenEmpty 下拉框 支持 最大长度 超出... vue 组件

<template>
  <Select v-model="innerValue"
          :disabled="disabled"
          :clearable='clearable'
          @on-change="onChangeHandle">
    <Option v-for="item in this.selectList"
            :title="item.nameTitle"
            :value="item.code"
            :key="item.code"> {{ item.nameLimit }}
    </Option>
  </Select>
</template>

<script>
export default {
  name: 'SelectZenEmpty',
  components: {},
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      nameMaxSingleLength: 30,
      innerValue: '',
      selectList: []
    }
  },
  watch: {
    value (val) {
      this.innerValue = val
    }
  },
  computed: {},
  methods: {
    getSingleLength2 (str, length) {
      let retLength = length
      let len = 0
      for (let i = 0; i < str.length; i++) {
        const c = str.charAt(i)
        if (escape(c).length > 4) {
          len += 2
        } else if (c !== "\r") {
          len++
        }
        if (len >= length) {
          retLength = i + 1
          break
        }
      }
      return retLength
    },
    getSingleLength (str) { // 中文2 英文 数字 1
      return str.replace(/[^\\x00-\\xff]/g, "00").length
    },
    nameByLimit (name) {
      if (this.getSingleLength(name) > this.nameMaxSingleLength) {
        const singleLength = this.getSingleLength2(name, this.nameMaxSingleLength - 2)
        console.info('singleLength', singleLength)
        return name.substring(0, singleLength) + '...'
      } else {
        return name
      }
    },
    nameByTitle (name) {
      if (this.getSingleLength(name) > this.nameMaxSingleLength) {
        return name
      } else {
        return ''
      }
    },
    setSelectList (arr) {
      if (arr.length > 0) {
        this.selectList = arr.map(item => {
          return {
            ...item,
            nameTitle: this.nameByTitle(item.name),
            nameLimit: this.nameByLimit(item.name)
          }
        })
      } else {
        this.selectList = arr
      }
      console.info('setSelectList this.selectList', this.selectList)
    },
    getItem (code) {
      console.info('getItem code', code)
      console.info('selectList', this.selectList)
      return this.selectList.filter(item => {
        return item.code === code
      })[0]
    },
    onChange (code) { },
    onChangeHandle (code) {
      console.info('onChangeHandle', code)
      // console.info('onChange', this.onChange)
      this.$emit('input', code)
      this.$emit('getItem', this.getItem(code))
      this.onChange(code)
    }
  },
  created () { },
  activated () { },
  mounted () { },
  beforeDestroy () { }
}
</script>

<style>
</style>
posted @ 2021-12-24 11:36  彭成刚  阅读(96)  评论(0编辑  收藏  举报