Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

VueJS Watched Property

A watched property is a property whose value is monitored for updates and is assigned a function that should be called when the value changes. For example, if you are working on an application for displaying exchange rates, you can use a watched property to make API calls in the background when the entered amount changes.

In this lesson, you will learn how to work with watched properties in Vue JS.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - this is mainly needed for development purposes only. You need NPM which comes with Node to work with tools like Vue CLI
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.
  • HTML & CSS Basics - this is an added advantage. Vue works on the HTML elements to manipulate them. The styling is done using CSS so you must be familiar with the basics

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called vue-components

Open the directory vue-components in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • index.html - this is the file that will contain our application source code

The following visualizes our project setup

vue-components
-index.html

How Watched Properties Work

Properties in Vue JS are defined in the data section of the Vue instance initialization parameter. Vue also has another parameter watch that we can use to define watchers. This is done by creating a function within the watch parameter with the same name as that of the property that we want to watch.

The following snippet shows how we do it.

let vm = new Vue({
    el: 'root',
    data: {
        message = 'The watcher'
    },
    watch: {
        message: function(){
            console.log('The value of message has changed');
        }
    }
})

HERE,

  • data: {...} defines a property message that is assigned a string value
  • watch: {...} defines a watch function that has the same name as the property message. The function simply logs a message to the console for now. You can make it do whatever you want to happen when the value of message changes.

So if we change the value of message in the console like so

vm.message = 'The Watcher'

You should be able to get the following message printed in the console

The value of message has changed
"The Watcher"

In the next section, we will create an application that uses watched properties

Watched Property Example

We will create a simple forex exchange application that will convert as the user is typing in the input box.

Open the file index.html and add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Watched Property</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            Amount In USD : <input type = "text" v-model = "amount">
            <p>Amount in ZMK: {{amount_in_local}}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    amount: 0,
                    amount_in_local: 0
                },
                watch: {
                    amount: function(){
                        this.amount_in_local = this.amount * 16;
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • data: {...} defines two properties amount and amount_in_local that have both been initialized to the value 0.
  • watch: {...} defines a watch function amount that watches the value of the property amount. Inside the callback function, we are simply multiplying the value of amount with a static exchange rate of 16 and assigning the result to the property amount_in_local.
  • Amount In USD : <input type = "text" v-model = "amount"> uses the v-model directive to bind the value of amount to the input element.
  • <p>Amount in ZMK: {{amount_in_local}}</p> displays the value of the variable amount_in_local.

Open the file index.html in the web browser

You should be able to get the following results

{{image placeholder}}

Computed Vs Watched Properties

In the previous lesson, we looked at computed properties. Watched properties are similar to computed properties because they both respond to value changes in properties that they depend on. You do not need to explicitly call the computed or watched property function. They are fired automatically.

Watched properties only watch a single property while a computed property can have a number of properties that it is dependent on. For example, you can create watched properties for properties first_name and last_name where as with computed properties, you can have both first_name and last_name in the same computed property.

You should generally use computed properties when you want to apply some business logic to properties before displaying the result to the user. Watched properties are useful in cases where you want to perform a special operation when a value of a property changes. For example, you can watch the value of a property currency and when the value changes you can make an API call from the watched property function to fetch the exchange rate.

Summary

Watched properties have callback functions that are executed automatically when the value of the property changes. The property and the watched property function must have the same name. Watched properties are similar to computed properties in the sense that they both respond to data value changes. Watched properties deal with a single property only while computed properties can respond to changes in more than one property.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

VueJS Computed Properties

VueJS Data Binding

Leave A Reply