Reputation: 63
I have a search input.
Each keystroke on this input emit an event "search" ($emit Vue.js function).
I have another component listening on this event ($on Vue.js function), then call a search web service and display the result.
(the events are send on a bus, here a simple Vue instance).
This works well.
I want to emit the search event only if no key press has been made for a delay, let's say 200ms. That way, if I quicly type a word in the search input, only one event will be sent. And if I'm slow, I still will have search results while typing.
How can I achieve that ?
Upvotes: 1
Views: 961
Reputation:
I'm using underscore's .debounce()
method for these purposes. Demo:
new Vue({
el: '#app',
data: {
query: ''
},
methods: {
updateQuery: _.debounce(function (evt) {
this.query = evt.target.value
// Call your AJAX here. For example:
// if (this.query.length) this.$store.dispatch('loadItems')
}, 300),
clearQuery () {
this.query = ''
}
}
})
[v-cloak] {
display: none;
}
<div id="app">
<input
type="text"
@input="updateQuery"
:value="query"
placehorder="search..."
>
<button @click="clearQuery">clear</button>
<p v-cloak>You are looking for {{ query }}</p>
</div>
<script src="https://unpkg.com/[email protected]/underscore-min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
If you want to be more effective, use Lodash. It is the same thing, but Lodash is modular, so you can add to your project only modules you need, and not the complete library. For .debounce() method is there separate javascript:
<script src="https://unpkg.com/[email protected]/debounce.js"></script>
Upvotes: 2