Blog>
Snippets

Creating a New Vue.js Component and Watching Reactive Changes

Demonstrate how to create a basic Vue.js component and use the watchEffect function to observe reactive changes in the Virtual DOM.
<!DOCTYPE html>
<html>
<head>
    <title>Vue.js Component</title>
</head>
<body>
    <div id="app">
        <user-profile :username="'JohnDoe'" />
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.min.js"></script>
    <script>
        Vue.component('user-profile', {
            props: ['username'],
            template: `<div>
                <h1>{{ fullName }}</h1>
            </div>`,
            data() {
                return {
                    firstName: this.username,
                    lastName: 'Smith' 
                };
            },
            computed: {
                fullName() {
                    return this.firstName + ' ' + this.lastName;
                }
            },
            watch: {
                firstName(newVal, oldVal) {
                    console.log(`firstName changed from ${oldVal} to ${newVal}`);
                }
            }
        });

        new Vue({
            el: '#app'
        });
    </script>
</body>
</html>
This HTML document includes a Vue.js component with a script that registers a 'user-profile' component, which has a 'username' prop, a computed property for the 'fullName', and a watcher that logs changes to 'firstName'. In the Vue instance, this component is used and provided a username prop. Vue.js library is included from a CDN.
<style>
h1 {
    color: #333;
}
</style>
CSS styles for the h1 element to set the text color.