前言
elementUI el-select设置allow-create属性时,创建新条目限制空格
碰到了需求,心血来潮记录一下使用
一、自定义指令
1.代码如下(示例):
<el-select
v-model="value"
v-no-empey
filterable
clearable
allow-create
>
<el-option v-for="item in options" :key="item.code" :label="item.name" :value="item.code" />
</el-select>
<script setup >
// vue3 自定义指令-限制下拉
const vNoEmpey = {
mounted(el, binding) {
function selectKeyDown(e) {
if (e.key === ' ') {
e.preventDefault()
}
}
el.selectKeyDownFn = selectKeyDown
el.addEventListener('keydown', selectKeyDown)
},
beforeUnmount(el) {
if (el.selectKeyDownFn) {
el.removeEventListener('scroll', el.selectKeyDownFn)
delete el.selectKeyDownFn
}
}
}
<script />
二、局部限制单个el-select
1.代码如下(示例):
<el-form-item label="商品类型:" prop="productType">
<el-select
ref="eleSelect" //这里很重要1
v-model.trim="formData.productType"
placeholder="请选择"
filterable
clearable
@input.native="trimSelect" //这里很重要2
>
<el-option
v-for="item in dictList.SPLX"
:key="item.dictId"
:label="item.dictLabel"
:value="item.dictValue"
></el-option>
</el-select>
</el-form-item>
// 开头为空格时重新赋值为空
const eleSelect = ref()
const trimSelect = ()=>{
let regex = /^\s*$/;
if(regex.test(eleSelect.value.selectedLabel)){
eleSelect.value.selectedLabel = ''
}
}