el-select可搜索,可新增,可编辑

admin2024-08-23  6

<template>
  <el-select
    ref="select"
    v-model="select"
    filterable
    allow-create
    default-first-option
    @visible-change="(val) => visibleChange(val)">
    <el-option
      v-for="item in optionsSelect"
      :key="item.value"
      :label="item.label"
      :value="item.value"/>
  </el-select>
</template>
 
<script>
export default {
  name: 'SelectInput',
  data() {
    return {
      select: '',
      optionsSelect: [{
        label: '黄金糕',
        value: '黄金糕'
      },
      {
        label: '双皮奶',
        value: '双皮奶'
      }]
    }
  },
  mounted() {
    this.$refs.select.$children[0].$refs.input.addEventListener('input', this.inputValue, false)
  },
  beforeDestroy() {
    this.$refs.select.$children[0].$refs.input.removeEventListener('input', this.inputValue, false)
  },
  methods: {
    inputValue() {
      this.$nextTick(() => {
        this.select = this.$refs.select.$children[0].$refs.input.value
      })
    },
    visibleChange(val) {
      if (val) { // 下拉框展开
        const selectionStart = this.$refs.select.$children[0].$refs.input.selectionStart
        console.log(selectionStart)
        this.$nextTick(() => {
          const inputElement = this.$refs.select.$children[0].$refs.input
          inputElement.value = this.select
          inputElement.setSelectionRange(selectionStart, selectionStart)
          inputElement.focus()
          // 计算滚动位置
          const characterWidth = inputElement.scrollWidth / inputElement.value.length
          const scrollPosition = (selectionStart + 1) * characterWidth - inputElement.offsetWidth / 2
 
          // 确保滚动位置不超过边界
          const maxScrollPosition = inputElement.scrollWidth - inputElement.offsetWidth
          inputElement.scrollLeft = Math.min(maxScrollPosition, scrollPosition)
        })
      } else { // 下拉框关闭
        this.$nextTick(() => {
          if (this.$refs.select.$children[0].$refs.input === document.activeElement) {
            this.$refs.select.toggleMenu()
            this.$refs.select.blur()
          }
        })
      }
    }
  }
}
</script>

上面情况时会有bug

change事件 没有值时,this.select = ''   

当绑定的其他页面值时,visibleChange事情里也加一层if(this.select = '')  为空则  赋值为中间转换值

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!