联想式搜索框,也有人叫仿百度式搜索框,用户输入想搜索的部分内容就可以显示所有包含输入内容的结果,用户每次输入都会调用后端接口模糊查询,这样可以加快页面第一次打开时的速度,可以使用elementUI中Select选择器的远程搜索实现。
dom层:
与一般的element下拉框相比需要加上remote和:remote-method这两个参数。
<template>
<el-select
v-model="value"
multiple //是否多选
filterable //是否可搜索
remote //是否为远程搜索
reserve-keyword //多选且可搜索时,是否在选中一个选项后保留当前的搜索关键词
placeholder="请输入关键词"
:remote-method="remoteMethod" //远程搜索方法
:loading="loading"> //页面加载转圈
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
js:
需要两个方法,remoteMethod方法用来调用后端接口,根据传入的name请求接口进行模糊查询,并将查询到的结果赋值给下拉框的option变量;remoteClear方法用来清除option变量的值,如果输入的值为空则执行。
remoteMethod(query) {
if (query !== '') {
this.loading = true;
setTimeout(() => {
getData({name:query}).then(res=>{
this.loading = false;
this.options = res.data;
})
}, 200);
} else {
this.remoteClear();
}
}
remoteClear(){
this.option = [];
}