A short introduction to Vue.js watchers

/ #Vue.js


When you're working with Vue.js you often need to run a function when a certain value changes. Vue.js watchers helps you with that.

A quick example of Vue.js watch

I'm going to start with showing you a little example of a Vue.js watcher.

<template>
    <p>Number of clicks: {{ clicks }}</p>
    
    <button @click="increaseClick()">Increase click</button>
</template>

<script>
export default {
    data() {
        return {
            clicks: 0 // Number of clicks
        }
    },
    methods: {
        increaseClick: function() { // Method for increasing the number of clicks
            this.clicks += 1 // Add one click
        }
    },
    watch: { // Here we define the watchers
        clicks: function() { // We add a watcher to the "clicks" variable, this will be called when clicks changes
            console.log('Num clicks: ' + this.clicks) // Log the output to the browser's console
        }
    }
}
</script>

The first thing we do in this example is to create a simple paragraph showing the current number of clicks. We also added a button which calls the function increaseClick when you click it.

Old value

If you want to be able to know what the old value was when the watch function is called you can do this by added a second parameter to the function like this.

watch: {
    clicks: function(newVal, oldVal) {
        console.log('New value: ' + newVal)
        console.log('Old value: ' + oldVal)
    }
}

What to use it for?

First I have to say that you should not try to change the value of this.clicks inside the watch function. If you do this then there will be a endless loop and your browser will crash.
You should be a little bit careful about using the watch function too much. One of the most common usage of this function is for example if you want to perform a ajax request when the user finishes typing on the keyboard. Here is a cool example of this.

<div id="app">
    <p>Search:</p>
    <input type="text" v-model="query">
    <p>{{ result }}</p>
</div>

<!-- Include the Vue -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<!-- Include lodash (A modern JavaScript utility library delivering modularity, performance & extras.) -->
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
<!-- Our script -->
<script>
new Vue({
    el: '#app',
    data: function() {
        return {
            query: '',
            result: 'Write a search term'
        }
    },
    watch: {
        query: function() {
            // When we start typing we show this message as the temporary search result
            this.result = 'We will start searching when you stop typing!'
            // Call the debouncedPerformSearch function (debounce will make sure that it is not called
            // before after 500ms after the last key is clicked)
            this.debouncedPerformSearch()
        }
    },
    created: function() {
        // _.debounce is a function which comes from the lodash script we included.
        // It's created to that we can limit how often a function is called.
        // You don't want your site to perform a heavy operation like a search 
        // everytime a key is clicked. This function makes it possible to only
        // perform the search 500 milliseconds after the last key is clicked.
        
        // When our Vue instance is created, we set that debouncedPerformSearch is a function
        // that calls the debounce function, which again calls the performSearch function after 500 ms
        this.debouncedPerformSearch = _.debounce(this.performSearch, 500)
    },
    methods: {
        performSearch: function() {
            if (this.query) { // Check if query is set
                this.result = 'Searching...' // Set the result text to Searching... while we wait for the "server"
            }
            
            // You will usually call a API or something here...
            
            // This is just for demo purpose, reset the result text after 2000 milliseconds
            setTimeout(() => {
                this.result = 'Write a search term'
            }, 2000);
        }
    }
})
</script>

Other Vue.js tutorials

-Introduction to Vue.js props
-Vue.js filters

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.