Vue.js Explained
Key Concepts
Vue.js is a progressive JavaScript framework for building user interfaces. The key concepts include:
- Reactivity
- Components
- Directives
- Templates
- Lifecycle Hooks
Reactivity
Vue.js automatically tracks changes to data and updates the DOM accordingly. This is known as reactivity.
<div id="app"> <p>{{ message }}</p> <button @click="changeMessage">Change Message</button> </div> <script> new Vue({ el: '#app', data: { message: 'Hello, Vue.js!' }, methods: { changeMessage() { this.message = 'Message changed!'; } } }); </script>
Components
Components are reusable Vue instances with a name. They allow you to build complex UIs by breaking them into smaller, manageable pieces.
<div id="app"> <my-component></my-component> </div> <script> Vue.component('my-component', { template: '<div>A custom component!</div>' }); new Vue({ el: '#app' }); </script>
Directives
Directives are special attributes with the v- prefix. They apply special reactive behavior to the rendered DOM.
<div id="app"> <p v-if="show">This message is shown if 'show' is true.</p> <button @click="toggle">Toggle Message</button> </div> <script> new Vue({ el: '#app', data: { show: true }, methods: { toggle() { this.show = !this.show; } } }); </script>
Templates
Vue.js uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying Vue instance's data.
<div id="app"> <p>{{ message }}</p> </div> <script> new Vue({ el: '#app', data: { message: 'Hello, Vue.js!' } }); </script>
Lifecycle Hooks
Lifecycle hooks are special methods that get called at different stages of a component's lifecycle, such as creation, mounting, updating, and destruction.
<div id="app"> <p>{{ message }}</p> </div> <script> new Vue({ el: '#app', data: { message: 'Hello, Vue.js!' }, created() { console.log('Component created!'); }, mounted() { console.log('Component mounted!'); } }); </script>
Examples and Analogies
Imagine building a house:
- Reactivity: Think of it as a smart home system that automatically adjusts the lights and temperature based on your presence.
- Components: Think of each room in the house as a component, each with its own purpose and functionality.
- Directives: Think of directives as switches that control specific features in the house, like turning on the lights or opening the blinds.
- Templates: Think of templates as the blueprints that define the structure and layout of the house.
- Lifecycle Hooks: Think of lifecycle hooks as the stages of construction, from laying the foundation to painting the walls.