keyup事件规避多次调用服务

2017-08-14  本文已影响53人  jinya2437

背景:vue2.0框架

目前存在的问题

  1. 键盘每押下一次调用接口,请求频率过高,增加服务器压力
  2. 多次调用接口,响应时间短的先返回,响应顺序和请求顺序对应不上。

如下图所示:

1.png
把响应的数据打印到控制台,发现响应顺序和请求顺序不一致,第一个发起的请求是响应最慢的。导致页面展示的数据不正确

解决方案1

// search.vue
<template>
  <input id="keyword" v-model="keyword" type="text" @keyup.stop="keyup">
</template>

<script>
export default{
  data() {
    suggestList:[],
    keyword:""
  },
  methods:{
    keyup(){
      let curVal = this.keyword;
      let that = this;
      // 延迟0.5秒请求服务,记录当前的值
      this.keyUpTimeout = setTimeout(function() {
        that.suggestAjax(curVal);
      }, 500)
    },
    suggestAjax(curVal) {
      // 如果0.5秒内值没有改变,则发送请求
      if(curVal === this.keyword && this.keyword.trim().length > 0) {
        searchApi.searchSuggest(this.keyword)
        .then((res) => {
          if(data.result.code == 200) {
          this.suggestList = data.data;
          }
        })
        .catch((error) => {
          console.log(error);
        })
      }
    } 
  }
}
</script>

解决方案2

lodash官网:https://lodash.com/

Lodash提供了函数节流(throttle)、函数去抖(debounce)等。这里使用函数节流(throttle)解决上述问题。

安装Lodash

npm install lodash

使用throttle

// search.vue
<template>
  <input id="keyword" v-model="keyword" type="text" @keyup.stop="keyup">
</template>

<script>
// 引入节流函数
import { throttle } from 'lodash'
export default{
  data() {
    suggestList:[],
    keyword:""
  },
  methods:{
    // 使用节流函数,设置在0.5秒内只发一次请求
    keyup:throttle(function(){
      this.suggestAjax();
    },500),
    suggestAjax() {
      if(this.keyword.trim().length > 0) {
        searchApi.searchSuggest(this.keyword)
          .then((res) => {
            if(data.result.code == 200) {
              this.suggestList = data.data;
            }
          })
         .catch((error) => {
            console.log(error);
          });
      }             
    }
  }
}
</script>

如下图所示:发了三次请求

2.png
上一篇 下一篇

猜你喜欢

热点阅读