vue項目中,用戶輸入關鍵字搜索,並且手機端做無限下拉
watch: { 'getListForm.searchKey'(val) { this.radioChange(); // 還有其他邏輯,內部調用getDeviceList } }
1 getDeviceList() { 2 apiGetDeviceList(Qs.stringify(this.getListForm)).then(res => { 3 if (this.getListForm.pageNumber === 1) { // 搜索第一頁 清空 4 this.deviceList = []; 5 } 6 this.deviceList.push(...res.list); // 數組合並 7 if (res.totalPage === 1 || res.totalPage < this.getListForm.pageNumber) { 8 this.loading = false; 9 this.finished = true; 10 } 11 this.loading = false; 12 this.getListForm.pageNumber++; 13 }) 14 },
后來測試同學發現問題,當用戶輸入過快,網絡緩慢的情況下,搜索結果不准確,由於上一次輸入結果沒有及時返回,導致多次插入數組
解決方案如下
1 watch: { 2 'getListForm.searchKey'(val) { // 判斷用戶停止輸入 val值是為此次監控的值,但是input 綁定的this.getListForm.searchKey 卻是雙向輸入,那么每隔500毫秒檢測一次,直到用戶停止輸入 3 setTimeout(() => { 4 if (val === this.getListForm.searchKey) { 5 this.radioChange(); 6 } 7 }, 500) 8 } 9 }