# 点击 clearable 清除按钮输入建议失效
我们会发现,如果给 el-autocomplete 组件标签加上 clearable 属性以后,那么,当我们输入内容以后,再点击 clearable 清空按钮清空输入框中输入的数据以后,当我们再重新输入文字的时候,请求会触发,后端返给我们的数据也获取到了,但是后端返回给我们的数据却没有渲染到页面上。就仿佛输入没反应了。解决方案比较直接的就是,当用户点击了 clearable 清空按钮以后,就让当前获取焦点的输入框失去焦点,回到最初状态,一切重新开始
即为:主动触发失去焦点,解决‘fetch-suggestions’输入建议失效的 bug,也就是: @clear="blurForBug()"
| <template> |
| <div id="box"> |
| <el-autocomplete |
| :fetch-suggestions="querySearch" |
| v-model="inputValue" |
| @select="handleSelect" |
| :debounce="0" |
| :trigger-on-focus="true" |
| clearable |
| @clear="blurForBug()" |
| ></el-autocomplete> |
| </div> |
| </template> |
| blurForBug(){ |
| document.activeElement.blur() |
| } |
# 传递多个参数(使用闭包)
html 部分
| <el-autocomplete |
| v-model="inputValue" |
| @select="handleSelect" |
| :debounce="0" |
| :trigger-on-focus="true" |
| clearable |
| @clear="blurForBug()" |
| :fetch-suggestions=" |
| (queryString, cb) => { |
| multipleFn(queryString, cb, index); |
| } |
| " |
| ></el-autocomplete> |
js 部分
| multipleFn(queryString, cb, index) { |
| console.log(queryString, cb, index) |
| } |
# 整体代码附上
| <template> |
| <div id="box"> |
| <el-autocomplete |
| :fetch-suggestions="querySearch" |
| v-model="inputValue" |
| @select="handleSelect" |
| :debounce="0" |
| :trigger-on-focus="true" |
| clearable |
| @clear="blurForBug()" |
| ></el-autocomplete> |
| </div> |
| </template> |
| |
| <script> |
| export default { |
| data() { |
| return { |
| inputValue: "", |
| }; |
| }, |
| methods: { |
| |
| querySearch(queryString, cb) { |
| console.log("如何触发", queryString, cb); |
| if (queryString == "") { |
| cb([{ value: "历史记录一" }, { value: "历史记录二" }]); |
| } else { |
| let apiResult = [ |
| { |
| value: "老王", |
| }, |
| { |
| value: "王老吉", |
| }, |
| ]; |
| |
| setTimeout(() => { |
| |
| cb(apiResult); |
| }, 500); |
| } |
| }, |
| |
| handleSelect(item) { |
| console.log("拿到数据", item); |
| }, |
| |
| |
| |
| blurForBug(){ |
| document.activeElement.blur() |
| } |
| }, |
| }; |
| </script> |
| |
| <style lang="less" scoped> |
| #box { |
| width: 100%; |
| height: 600px; |
| box-sizing: border-box; |
| padding: 50px; |
| } |
| </style> |