延遲搜索邏輯實現

簡介

在移動端或者pc端有時候要作實時搜索的效果,即根據用戶輸入的內容,實時調取接口得到相關的列表。可是咱們並不但願每增長或者減小一個字就立馬調取接口,由於這樣請求次數太多並且打字速度快的話會不斷的請求很耗性能,因此咱們但願可以在打字結束後的一段時間內發起請求,儘可能少的調取接口vue

效果如圖:性能

實現邏輯

我是使用的vue,因此如下均爲vue代碼優化

下面講一下邏輯流程this

1.雙向綁定輸入框內的數據,使用watch監聽輸入框內數據的變化spa

2.在data中定義變量timer: null3d

3.當監聽到輸入框內變化時給timer定義一個延時器,具體延遲時間能夠本身定,用以延遲觸發調用接口雙向綁定

4.僅這樣作並不能達到想要的效果,由於每一次改變仍是會調用接口,關鍵的是要在監聽到輸入框改變的時候判斷timer 是否存在若是存在就將上一次的延時器清除,由於上一個延時器延遲300ms的緣故,因此搜索不會當即觸發,清除定時器後就不會再去請求接口,這樣就能夠實現延時搜索code

參考代碼以下:blog

<el-input type="text" class="myinput" placeholder="請輸入會員姓名或手機號" v-model="customer" clearable></el-input>
  watch: {
    customer() {
      this.showCustomerList = true
      let reg_number = /^[0-9]*$/
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.customer) {
        this.matchedCustomerList = []
        return
      } else {
        if (reg_number.test(this.customer)) {
          if (this.customer.length > 3) {
            this.timer = setTimeout(() => {
              this.search()
            }, 300)
          }
        } else {
          this.timer = setTimeout(() => {
            this.search()
          }, 300)
        }
      }
    }
  }

 

小結

這樣的搜索優化其實應該要注意的,就是這樣的小細節,讓用戶體驗和產品都有所提高接口

相關文章
相關標籤/搜索