el-select既能选择又能输入,并且再次点击时能接着编辑

1.实现效果

2.实现原理

1)el-select添加filterableallow-create之后可以输入内容;

2)再次输入时会将原来的内容变成提示,用户体验不好,因此需要找到办法将值重新赋给内部的input输入框,此处采用this.$refs.select.$children[0].$refs.input.value = this.select的方式将值重新赋给input输入框。

3)使用default-first-option之后可以确保按Enter键时能将内容输入,但是用户体验不好,因此使用this.$refs.select.$children[0].$refs.input.addEventListener('input', this.inputValue, false)方式将input输入框中的值实时赋值给绑定值select,用完记得在beforeDestroy()中移除监听。

3.代码

<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()
          }
        })
      }
    }
  }
}
</script>

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值