首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Vuejs和Axios发出多个get请求

Vuejs和Axios发出多个get请求
EN

Stack Overflow用户
提问于 2019-04-17 07:39:10
回答 3查看 905关注 0票数 4

我有一个简单的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)会在控制台中显示多个响应。

不管打字速度有多快,我怎么能只发出一次请求来得到一个问题的一个回答呢?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55717947

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档