VueJS Live search

Implementing live search is quite fun and easy with AngularJS thanks to the ng-model-options, to which you may apply a debounce (delay). Implementing something similar in VueJS however cannot be done out of box.

First, you need to import lodash (if not done yet). Don’t forget to run ‘npm install lodash’

// import lodash 
import _ from 'lodash'

Create your input

<template>
    <div class="form-group">
        <input type="text" v-model="keywords"  
            class="form-control input-lg" />
    </div>
</template>

Now you can debounce the s**t out of it!

<script>
import _ from 'lodash'
import axios from 'axios'

export default {
    data () {
        return {
            keywords: "",
            results: []
        }
    },

    methods: {
        searchAfterDebounce: _.debounce(
            function () {
                this.search()
            }, 500 // 500 milliseconds
        ),

        search () {
            if (keywords.length > 1) {
                axio.get('/api/v1/url').then(response => {
                   this.results = response.data
                })
            }
        }
    },

    watch: {
        keywords: function (val) {
            this.searchAfterDebounce()
        }
    }
}
<script>

All we are doing is waiting for the user to take half-a-second break when typing, then we check if there more than 1 characters typed. If true, we call the API and pass the results to the results variable.

Yeah and Madrid lost to Barcelona tonight 2-3. We are now 2nd. Ramos, again, took a red card; Messi (the extraterrestrial) scored a brace, including his late winner at the 92″. Hala Madrid!