irpas技术客

ElementUi el-autocomplete 踩坑 (使用clearable清除,点击输入框下拉条件不再显示)_流浪码农~_el-autocomplete

irpas 6727

今天在写组件的时候,用到了el-autocomplete来做模糊搜索。因为要可以清除条件,所以加了clearable属性,然后遇到了个bug。点击清除图标后,如果你已经是聚焦状态了,你在点击输入框,下拉框不会再显示了

查了一下,是因为有element-ui源码有bug,主要原因是

参考该博客

autocomplete组件在执行清除事件时,将activated置为false。这时候下拉框不会显示了,而在querySearch执行成功后又没有将activated置为true。所以导致了该bug。解决的核心思路就是想办法把this.activated的值设置为true。或者是清除完后让输入框失去焦点。

解决办法有两种:

1.给el-autocomplete添加一个ref。在清除事件后调用 this.$refs.el_auto.activated = true

<el-form-item :label="$t('code_begin')" v-if="popoverForm.hasOwnProperty('code_begin')"> <el-autocomplete class="inline-input" v-model="popoverForm.code_begin_text" :fetch-suggestions="querySearch" size="medium" :placeholder="$t('code_begin')" @select="handleSelect($event,'begin')" clearable @clear="clearSelect('begin')" ref="el_auto" value-key="acc_title" > <i slot="suffix" class="el-input__icon el-icon-notebook-2 icon-style" @click="openChooseAccDialog('begin')" /> </el-autocomplete> </el-form-item> // clearable清除事件事件 clearSelect(type) { console.log('type', type) if (type === 'begin') { this.popoverForm.code_begin_text = '' this.popoverForm.code_begin = null // 主要代码 this.$refs.el_auto.activated = true } else if (type === 'end') { this.popoverForm.code_end_text = '' this.popoverForm.code_end = null } else if (type === 'acc_no') { this.popoverForm.acc_no_text = '' this.popoverForm.acc_no = null } else if (type === 'acc_subject') { this.popoverForm.acc_no_text = '' this.popoverForm.acc_no = null } else if (type === 'assist_item_no') { this.popoverForm.assist_item_text = '' this.popoverForm.assist_item_no = null } this.$forceUpdate() },

2.在清除事件里调用document.activeElement.blur()

因为我的控件使用到了多个el-autocomplete。每个都加上ref比较麻烦。所以使用该方法,只有一行代码。 将聚集的输入框失去焦点即可。

// clearable清除事件事件 clearSelect(type) { console.log('type', type) if (type === 'begin') { this.popoverForm.code_begin_text = '' this.popoverForm.code_begin = null } else if (type === 'end') { this.popoverForm.code_end_text = '' this.popoverForm.code_end = null } else if (type === 'acc_no') { this.popoverForm.acc_no_text = '' this.popoverForm.acc_no = null } else if (type === 'acc_subject') { this.popoverForm.acc_no_text = '' this.popoverForm.acc_no = null } else if (type === 'assist_item_no') { this.popoverForm.assist_item_text = '' this.popoverForm.assist_item_no = null } console.log('focus', document.activeElement) // 主要代码 // document.activeElement获得了DOM中被聚焦的元素;.blur()取消聚焦 document.activeElement.blur() this.$forceUpdate() },

这里做个记录,el-autocomplete接收的数组需要是 value属性才能显示。 但其实提供了一个value-key 属性,可以指定对应的key。 因为之前不知道有value-key属性,我还将调用接口获得的数据进行了转换。QAQ


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #elautocomplete #禁用下拉 #所以导致了该bug #解决的核心