问题:使用ant-design中select的search方法,添加模糊搜索时,接口即时请求了,但是页面绑定的数据未更新为最新的(比如: 按键输入123时,需要展示为“123”的搜索结果空数组,但是页面并没更新为空);经排查发现此次模糊搜索会发送三个接口请求,但是“123”无结果数据,“1”的有数据返回最慢,导致页面绑定的变量展示的是“1”的搜索结果。
解决办法:
<a-select placeholder="请选择对象名称"
showSearch
:filterOption="false"
:getPopupContainer="triggerNode => triggerNode.parentNode"
@search="queryObjectName"
@dropdownVisibleChange="queryObjectNameA"
@change="changeObjectName">
<a-spin v-show="objectNameLoading"
slot="notFoundContent"
size="small" />
<span v-show="!objectNameLoading"
slot="notFoundContent">暂无数据</span>
<a-select-option v-for="(item, index) in objectNameArr"
:key="index + item.id"
:value="item.id">
<span v-show="item.roleName">{{item.roleName}}</span>
<span v-show="!item.roleName">{{item.username}}</span>
</a-select-option>
</a-select>
queryObjectName: debounce(function (str) {
// 此处加防抖,0.5s内只触发最新的一次(即0.5s之内输入“123”的时候只请求“123”的数据,不请求“1”和“12”的了)
this.objectNameArr = []
this.objectNameArr.length = 0
this.$forceUpdate()
this.objectNameLoading = true
// 通过str请求数据
}, 500),
queryObjectNameA (bool) {
if (!Boolean(bool)) {
return false
}
this.objectNameArr = []
this.objectNameArr.length = 0
this.$forceUpdate()
this.objectNameLoading = true
// 请求数据,此时查询入参为空字符串
}
/**
* 函数防抖 使用方式(method里面): infoMe: debounce(fun, 1000)
* @param {*} fn 执行函数
* @param {*} del 延迟时间
*/
export function debounce(fn, delay = 500) {
let timer = null
return function() {
const args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn.apply(this, args) // this 指向vue
}, delay)
}
}