1.template中
<el-row>
<el-col :span="24">
<label for="search">一键查询</label>
<el-autocomplete
ref="myAutocomplete"
v-model="searchKey"
:fetch-suggestions="querySearch"
:trigger-on-focus="true"
clearable
placeholder="搜索 | 查找关键字"
size="medium"
@clear="clearInput"
@select="search"
@keyup.enter.native="search"
/>
<el-button id="search" :loading="searchLoading"
plain type="primary" @click="search">
查询
</el-button>
</el-col>
</el-row>
2.data中
searchKey: '',
searchLoading: false,
restaurants: [], // 智能提示列表数据,是一个数组对象
handleFocus: false,
3.methods中
/* 处理生成智能提示列表 */
querySearch(queryString, cb) {
const restaurants = this.restaurants;
const results = queryString ? this.createFilter(queryString) : restaurants;
// 调用 callback 返回建议列表的数据
cb(results);
// 至关重要,这是当点击清空按钮后,再次聚焦一次输入框,然后聚焦后把handleFocus设置为false,就不自动聚焦,如果没有此步骤,就会点击清空按钮后不提示了
if (this.handleFocus) {
this.$refs.myAutocomplete.handleFocus();
this.handleFocus = false;
}
},
/* 处理智能列表数据 */
createFilter(queryString) {
let temp = this.restaurants.filter(item => {
return item.value.toLowerCase().includes(queryString.toLowerCase());
});
let res = temp.sort(function (a, b) {
// 按照名称升序
return a.value.localeCompare(b.value);
});
return res;
},
/* 当点击清空事件后,要再次调用该组件中的方法,进行聚焦 */
clearInput() {
this.handleFocus = true;
},