Skip to content

Instantly share code, notes, and snippets.

@miyataken999
Created September 9, 2018 16:07
Show Gist options
  • Save miyataken999/3fb0d4853b31334723c81b20e6a24f30 to your computer and use it in GitHub Desktop.
Save miyataken999/3fb0d4853b31334723c81b20e6a24f30 to your computer and use it in GitHub Desktop.
VueJS Search input with debounce
<h1 class="text-center">VueJS Search Input with Debounce</h1>
<p class="lead text-muted text-center">Using lodash _.debounce with a 1s delay</p>
<div id="app">
<my-list/>
</div>
const myList = Vue.component('MyComponent', {
name: 'myList',
template: `
<div>
<input
types="text"
class="form-control"
placeholder="Type here"
v-model="searchTerms"/>
<br/>
<ul class="list-group">
<li v-for="todo in filteredTodos" class="list-group-item">
{{ todo.title }}
</li>
</ul>
</div>
`,
data () {
return {
searchTerms: '',
todos: [
{ title: 'delectus aut autem' },
{ title: 'quis ut nam facilis et officia qui' },
{ title: 'fugiat veniam minus' },
{ title: 'et porro tempora' },
{ title: 'laboriosam mollitia et enim quasi adipisci quia provident illum' }
],
filteredTodos: []
}
},
watch: {
searchTerms (value) {
this.filterTodos(value)
}
},
methods: {
filterTodos: _.debounce(function (terms) {
this.filteredTodos = this.todos
.filter(item => {
const title = item.title.toLowerCase()
return terms ? title.includes(terms.toLowerCase()) : true
})
}, 1000)
},
created () {
this.filteredTodos = this.todos
}
})
new Vue({
el: '#app',
components: {
myList
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
body{
padding: 3rem;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment