Blog>
Snippets

Using watch to react to data changes

Provide an example of how to use 'watch' to execute code in response to changes in reactive data sources.
<html>
<head>
    <title>Watch Example</title>
    <script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
    <style>
        .notification {
            padding: 10px;
            background: #f1f1f1;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div id="app">
        <input v-model="message" placeholder="Type something..." />
        <div class="notification" v-if="notification">
            You modified the message!
        </div>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                message: '',
                notification: false
            },
            watch: {
                // Whenever `message` changes, this function will run
                message: function(newValue, oldValue) {
                    this.notification = true;
                    // Hide the notification after 2 seconds
                    setTimeout(() => this.notification = false, 2000);
                }
            }
        });
    </script>
</body>
</html>
This is a basic example of using Vue.js 'watch' feature to react to changes in data properties. It includes a text input bound to a message data property. A watcher is set up on the 'message' property that triggers a notification when the message changes. It uses a simple Vue instance, an input element with v-model directive, and conditional rendering for the notification. The CSS styles a notification area.