昨天做项目遇到一个新需求,就是将原来选择下拉框变成可搜索的,可模糊查询的。由于数据是键值对返回的,所以改起来很费劲。
我在想用AutoComplete虽然方便,但是这个方法就把键值对分开传值了,其他页面回显信息的时候也得大改,emmmm,恕小的比较懒。我想大家都不想改动代码,就还是用Select组件实现吧。以下是实现遇到得bug,一个让人头皮发麻的bug!!!
使用了select的属性:remote-method,来定义一个搜索的方法;on-chang定义选中选项的方法
<Select
clearable
filterable
transfer
remote
v-model="form.bussinessType"
placeholder="请选择"
style="width:155PX"
:remote-method="setQueryType"
@on-change="industryCate"
>
<Option
v-for="item in industryList"
:key="item.codeValue"
:value="item.codeValue"
>{{item.codeName}}</Option>
</Select>
但是这个方法执行后,就很神奇了,在我们搜到内容时是没有问题的,但是当我们按下选择哪一项时他就会自动在调用两次接口,导致我们的内容最后结果为空。
查阅了很多博客,最让我信服的就是说没有阻止watch监听,因为v-model每一次变化watch监听到都会刷新一次,所以我试了很多阻止watch的方法,但是都是不可以的。
然后回去继续看看这个官方文档,发现了一丝丝希望,是loading属性,它是来判断是不是处于搜索状态。
<Select
clearable
filterable
transfer
remote
v-model="form.bussinessType"
placeholder="请选择"
style="width:155PX"
:remote-method="setQueryType"
:loading="loadingType"
@on-change="industryCate"
>
<Option
v-for="item in industryList"
:key="item.codeValue"
:value="item.codeValue"
>{{item.codeName}}</Option>
</Select>
在选中选项的函数中取反,
industryCate(event) {
this.form.bussinessType = event
if(this.form.bussinessType){
this.loadingType = true
}
}
此时,还出现一个bug,就是你删除内容再次输入其他内容搜索时就不行了,所以此时要到搜索方法中将 loading 还原,让它可以继续进行下一次搜索。但是要加一个定时器,不然就会像原来一样执行三次的。
setQueryType(e) {
// e 是当前输入的值,
// this.form.bussinessType是已经选择的值
if(e!== this.form.bussinessType) {
setTimeout(()=>{
this.loadingType = false
},1000)
}
}