How to debounce (see only after finishing typing in the input) in VUEJS?

0

I come from AngularJS and, at certain times, when I need to query according to what the user is searching, I use ng-change , but I combine it with ng-model-options="{debounce: 500}" . This causes the angular queries not to fire off queries like crazy on my server, but it only makes the search done when it stops typing.

I wanted to do the same thing with Vue, but the option debounce was deprecated in version 2.0 +.

What now? How could I do in VueJS to be able to execute a @input only when the user stops typing?

Is there such a thing in VueJS ready, or will I have to do it "on hand"?

Example:

<input type="text" 
  v-model="pesquisa.nome" 
  @input="consultarSoQuandoPararDeDigitar()" />
    
asked by anonymous 10.10.2018 / 17:24

2 answers

2

You can do this using vue-rx that integrates rxjs to the life cycle of Vue components.

See an example working: link

Sample source code:

main.js

import Vue from "vue";
import VueRx from "vue-rx";
import App from "./App";

Vue.use(VueRx);

new Vue({
  el: "#app",
  components: { App },
  template: "<App/>"
});

App.vue

<template>
  <div id="app">
    <input type="text" v-stream:input="search$"> - debounced: {{ searchedValue }}
  </div>
</template>

<script>
import { debounceTime, pluck } from 'rxjs/operators';

export default {
  name: "App",
  domStreams: ['search$'],
  subscriptions,
  data,
  methods: {
    onSearch
  }
};

function subscriptions() {
  this.search$.pipe(
    debounceTime(300),
    pluck('event', 'target', 'value')
  ).subscribe(this.onSearch);
}

function data() {
  return {
    searchedValue: null
  }
}

function onSearch(value) {
  this.searchedValue = value;
}
</script>
    
11.10.2018 / 18:28
1

I decided to publish a response to record the way I solved the problem. I used a debounce technique for Javascript, based on setTimeout .

See:

new Vue({
  el: '#app',
  
  methods: {
    consultarQuandoParar: function consultarQuandoParar($event) {
      
      // Se chamar mais de uma vez, cancela a chamada anterior  
      
      console.log('digitou');
      clearTimeout(consultarQuandoParar.timeout);
      
      consultarQuandoParar.timeout = setTimeout(function () {
          console.log('parou de digitar e o resultado é "%s"', $event.target.value);
      }, 500);
    }
  }

})
<script
 src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script><divid="app">
  <input type="text" @input="consultarQuandoParar($event)" />
</div>

Basically, I call clearTimeout to cancel the last call of setTimeout that is assigned in the .timeout property. If the typing continues before the% s of% of the previous call ends, the call is always canceled. When you stop typing, it is executed.

So, with 500 being always canceled, allowing only the most recent to be executed, we have the effect of setTimeout for queries.

    
12.10.2018 / 02:31