Blog>
Snippets

Handling Events and Virtual DOM Updates

Showcase how to handle user input events and the subsequent VDOM updates by creating an interactive component.
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Event Handling and Virtual DOM Example</title>
    <style>
        #app {
            text-align: center;
            margin-top: 50px;
        }
    </style>
</head>
<body>
    <div id='app'>
        <!-- This input field will handle user typing events -->
        <input type='text' id='inputField' placeholder='Type something...' />
        <!-- This paragraph will display the typed text -->
        <p id='displayText'>Typed text will appear here</p>
    </div>

    <script src='https://unpkg.com/vue@2.6.12/dist/vue.js'></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                message: ''
            },
            watch: {
                // Reacting to data changes and updating the virtual DOM
                message: function(newValue) {
                    document.getElementById('displayText').innerText = `Typed text: ${newValue}`;
                }
            },
            methods: {
                // Handling the input event
                handleInput: function(event) {
                    this.message = event.target.value;
                }
            }
        });
    </script>
</body>
</html>
This code sets up a simple HTML structure for a Vue.js application. It includes an input field to capture user input and a paragraph to display the inputted text. Using Vue.js, it demonstrates handling the input event and updating the virtual DOM in response to data changes. As the user types in the input field, the displayed text updates in real time.