移動(dòng)端開(kāi)發(fā)過(guò)程中,總會(huì)遇到搜索功能的實(shí)現(xiàn),但這個(gè)過(guò)程會(huì)產(chǎn)生因快速搜索讓異步數(shù)據(jù)加載導(dǎo)致的List數(shù)組數(shù)據(jù)未清空從而導(dǎo)致數(shù)據(jù)多次push進(jìn)數(shù)組
如果手機(jī)端不停下拉刷新,由于數(shù)據(jù)都是異步加載的,這個(gè)過(guò)程會(huì)產(chǎn)生異步數(shù)據(jù)延時(shí),這時(shí)需要后端對(duì)查詢的數(shù)據(jù)進(jìn)行分頁(yè)處理
若后端沒(méi)做分頁(yè)處理,前端可以采取截流操作,即讓數(shù)據(jù)規(guī)定在多少秒以后才進(jìn)行數(shù)據(jù)加載,以免數(shù)據(jù)多次異步導(dǎo)致結(jié)果不受控制(即不知道什么時(shí)候結(jié)果能回來(lái))
這種情況在移動(dòng)端開(kāi)發(fā)也比較常見(jiàn),因此mark一下
以下實(shí)例的前提是 =>后臺(tái)對(duì)數(shù)據(jù)查詢做了分頁(yè)處理
頁(yè)面效果

頁(yè)面結(jié)構(gòu)
<template>
<div class="wbox warp choose">
<van-nav-bar :title="'選擇銀行'" fixed left-arrow left-text="返回" @click-left="onClickLeft" />
<van-search class="input" v-model="search" @focus='vFocusFn' placeholder="請(qǐng)輸入搜索關(guān)鍵詞" />
<div id='parentId'>
<mescroll ref="mescroll" @getData='getData()' warpId='parentId'>
<div class="bank_list">
<van-cell @click="chooseCity(item)" v-for="(item,cindex) in List3" :key="cindex" :title="item.BankName" />
</div>
</mescroll>
</div>
</div>
</template>
業(yè)務(wù)邏輯
getData (type) {
if (this.CurrentIndex === '0') {
this.List3 = []
}
const params = {
BankName: this.BankName, // 中國(guó)銀行名稱(chēng)關(guān)鍵字(支持模糊查詢)
CurrentIndex: this.CurrentIndex.toString(),
PageSize: '10'
}
this.$http.post('/eweb/eweb-transfer.BankQry.do', params).then(res => {
// 對(duì)異步加載數(shù)據(jù)做處理,否則出bug ---- 把快速觸發(fā)的getData的異步數(shù)據(jù)多次加在一起
if(type === 'watch'){
this.List3 = []
this.List3 = res.BankList
}else{
this.List3 = this.List3.concat(res.BankList)
}
this.CurrentIndex++
this.$nextTick(() => {
this.$refs.mescroll.mescroll.endSuccess(this.List3.length, this.List3.length < Number(res.TotalCount))
// this.$refs.mescroll.mescroll.endBySize(this.List3.length, Number(res.TotalCount)) // 后臺(tái)返回hasNextPage告知是否有下一頁(yè),或者前端這邊自己判斷
})
}).catch(() => {
this.$refs.mescroll.mescroll.endErr()
})
},
這里對(duì)異步數(shù)據(jù)做處理,如果是watch偵聽(tīng)到數(shù)據(jù)變化,則需要將list清空,因此給了個(gè)type判斷,這樣防止watch數(shù)據(jù)快速變化時(shí),異步加載的數(shù)據(jù)有可能未及時(shí)回來(lái)(其實(shí)是不知道異步數(shù)據(jù)什么時(shí)候回來(lái))第一次list清空了,后續(xù)第二次第三次第四次等不斷觸發(fā)加載的時(shí)候,CurrentIndex加1,這時(shí),則不符合index=== '0'的判斷,所以list3會(huì)多加一次或者多次異步加載回來(lái)的數(shù)據(jù)
正是因?yàn)楫惒郊虞d,導(dǎo)致數(shù)據(jù)未回來(lái),又做了一次新的數(shù)據(jù)getData,等上一次數(shù)據(jù)回來(lái)后,如果沒(méi)有if判斷,只有這一句代碼 this.List3 = this.List3.concat(res.BankList) ,這樣會(huì)把后續(xù)幾次觸發(fā)的數(shù)據(jù)都list3里
watch數(shù)據(jù)變化
watch: {
search (val) { // 需要注意,這里不給if判斷,只要數(shù)據(jù)有變化,不管有值還是為空,都作處理
this.CurrentIndex = '0'
this.BankName = val
this.List3 = []
this.getData('watch')
}
},