<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 = '') 为空则 赋值为中间转换值