Vuejs和Axios提出多个获取请求

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (418)

我有一个简单的Vue脚本,第一次学习Vue:

<!DOCTYPE html>
<html>
<head>
  <title>My first Vue app</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>
<body>
  <div id="watch-example">
      <p>
          Ask a yes/no question:
          <input v-model="question" type="text">
          <img v-bind:src="image">
      </p>
      <p>{{ answer }}</p>
  </div>
  <script>
    let watchExample = new Vue({

        // Root element of app
        el   : '#watch-example',

        // Properties keep track of
        data : {
            question : '',
            answer   : 'I cannot give you an answer until you ask a question!',
            image    : '',
        },
        watch : {
            question : function(newVal, oldVal) {
                const vm  = this;
                vm.answer = 'Waitinng for you to stop typing.';

                setTimeout(function() {
                    vm.getAnswer();
                }, 350);
            }
        },

        // App methods
        methods : {
            getAnswer: function() {
                const vm = this;

                if(!vm.question.includes('?')) {
                    vm.answer = 'Questions usually contain a question mark';
                    vm.image  = '';
                    return;
                }
                vm.answer = 'Thinking...';

                setTimeout(function() {
                    axios.get('https://yesno.wtf/api')
                        .then(function (response) {
                            vm.answer = response.data.answer;
                            vm.image  = response.data.image;
                        });
                }, 500);
            }
        }
    });
  </script>
</body>
</html>

我注意到当我输入一个问题时,包含一个问号(?),太快它会产生多个请求,我得到多个响应。它会在多个返回的响应中清除图像并添加新的响应。如果我慢慢输入一个问题,则只返回一个响应。

console.log(response) 显示控制台中的多个响应。

无论打字速度如何,如何只提出一个请求才能得到一个问题的答案?

提问于
用户回答回答于

目前,您只是通过将其包装在setTimeout中来延迟您的呼叫。我想你正在努力实现一个debounce效果。

Lodash具有此功能,但如果您还没有使用lodash并且不想将其包含在项目中,您可以轻松地在几行代码中编写它。

用户回答回答于

你需要的是debounce来自lodash

Vue文档中给出了一个很好的例子

注意这个特定的代码,作为一个例子:

created: function () {
    // _.debounce is a function provided by lodash to limit how
    // often a particularly expensive operation can be run.
    // In this case, we want to limit how often we access
    // yesno.wtf/api, waiting until the user has completely
    // finished typing before making the ajax request. To learn
    // more about the _.debounce function (and its cousin
    // _.throttle), visit: https://lodash.com/docs#debounce
    this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
  },

扫码关注云+社区

领取腾讯云代金券