代码改变世界

详细介绍:element里的select自定义输入的时候,不用点击下拉框选中自定义输入,而是当焦点失去的时候自动赋值输入的内容

2025-10-23 16:31  tlnshuju  阅读(24)  评论(0)    收藏  举报

在Element UI的el-select中,可以通过自定义失焦事件处理来实现当焦点离开时自动将输入内容赋值给选择框。

实现思路

  1. 使用el-select的filterableallow-create属性允许自定义输入

  2. 添加自定义输入框(如el-input)用于接收用户输入

  3. 监听输入框的blur事件,在失焦时将输入内容添加到选择框

代码实现

const receiverBlur = (event) => {
if(!event.target.value){
return
}
if((!queryParams.value.receiverName && event.target.value) || (queryParams.value.receiverName != event.target.value)){
queryParams.value.receiverName = event.target.value
}
}

完整代码

el-select失焦自动赋值
body {
font-family: 'Helvetica Neue', Arial, sans-serif;
padding: 20px;
background-color: #f5f7fa;
}
.container {
max-width: 600px;
margin: 0 auto;
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.demo-title {
text-align: center;
margin-bottom: 25px;
color: #409EFF;
font-weight: 500;
}
.select-container {
margin-bottom: 20px;
}
.custom-input {
margin-top: 15px;
}
.tip {
font-size: 13px;
color: #909399;
margin-top: 8px;
}
el-select失焦自动赋值示例
直接在输入框输入后,失去焦点即可自动添加
当前选中值: {{ selectedValue }}
选项列表: {{ options.map(o => o.label) }}
new Vue({
el: '#app',
data() {
return {
selectedValue: '',
customInput: '',
options: [
{ value: 'option1', label: '选项1' },
{ value: 'option2', label: '选项2' },
{ value: 'option3', label: '选项3' },
{ value: 'option4', label: '选项4' },
{ value: 'option5', label: '选项5' }
]
};
},
methods: {
// 处理el-select的失焦事件
handleBlur(event) {
const inputValue = event.target.value;
if (inputValue && !this.options.some(opt => opt.label === inputValue)) {
this.addNewOption(inputValue);
}
},
// 添加自定义输入选项
addCustomOption() {
if (this.customInput && !this.options.some(opt => opt.label === this.customInput)) {
this.addNewOption(this.customInput);
this.customInput = '';
}
},
// 添加新选项
addNewOption(label) {
const newOption = {
value: 'custom_' + Date.now(),
label: label
};
this.options.push(newOption);
this.selectedValue = newOption.value;
this.$message({
message: `已添加选项: ${label}`,
type: 'success',
duration: 2000
});
}
}
});

功能说明

  1. 上方el-select支持直接输入内容,失焦后自动添加为新选项

  2. 下方输入框可以输入自定义内容,失焦或点击右侧"+"按钮添加为新选项

  3. 添加新选项后会自动选中该选项并显示成功消息

注意事项

  • 需要添加filterableallow-create属性使el-select支持自定义输入

  • 通过监听blur事件捕获输入内容

  • 需要检查输入内容是否已存在,避免重复添加

  • 添加新选项后自动选中该选项提供更好的用户体验