-1

So on my website I have a input box

<SearchBox v-model="searchTerm"/>

Which I watch and call an url via Axios

watch: {
    searchTerm: function() {
      axios
      .get("https://robotic.buzz/skynet/search/" + searchTerm)
      .then(response => {
        // JSON responses are automatically parsed.
        this.results = response.data;
      })
      .catch(e => {
        this.errors.push(e);
      });
    }
  }

Is there a way to delay the call and cancel previous ones? So if someone types something in, when they pause for 1 second, it then calls the server and doesn't call it for every letter they enter.

A simple 1-second delay would still queue up the calls.

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
Burf2000
  • 5,001
  • 14
  • 58
  • 117
  • 4
    You would usually use a debounce for something like that. Try taking a look at [lodashes debounce](https://lodash.com/docs/4.17.10#debounce) function which you can [download from npm](https://www.npmjs.com/package/lodash.debounce) – craig_h Oct 08 '18 at 13:28
  • Looks a good solution how come you not posted it as one – Burf2000 Oct 08 '18 at 14:25
  • In addition: https://stackoverflow.com/questions/42199956/how-to-implement-debounce-in-vue2 – Philip Oct 08 '18 at 14:51
  • debounce fixed my issue perfectly – Burf2000 Oct 08 '18 at 19:35

1 Answers1

3

You could use the lazy modifier as follows :

 <input type="text"  v-model.lazy="searchTerm" />

So when you leave the text field you could watch the data and call axios

new Vue({

  el: '#app',
  data(){
  return{
  searchTerm:''
  }
  }
  ,
  watch: {
    searchTerm: function(val) {
    console.log(".")
      axios
      .get("https://robotic.buzz/skynet/search/" + val)
      .then(response => {
        // JSON responses are automatically parsed.
        console.log(response.data)
      })
      .catch(e => {
        this.errors.push(e);
      });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

<!-- Conversations -->

<div id="app">

<input type="text"  v-model.lazy="searchTerm" />

</div>
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164