Vue.js provides several built-in directives that offer powerful ways to manipulate the DOM. Directives are special tokens in the markup that tell the library to do something to a DOM element. In this section, we will cover the most commonly used built-in directives in Vue.js.
Key Built-in Directives
v-bind
v-bindThe v-bind directive is used to bind an attribute to an expression. This is commonly used to dynamically update the class, style, or other attributes of an element.
Example:
In this example, the div element will have the class active.
v-model
v-modelThe v-model directive creates a two-way binding on an input, textarea, or select element. This is particularly useful for form inputs.
Example:
Here, whatever you type in the input field will be reflected in the p tag.
v-if
v-ifThe v-if directive is used to conditionally render an element based on the truthiness of an expression.
Example:
If isVisible is true, the div will be rendered.
v-else
v-elseThe v-else directive must be used immediately after a v-if or v-else-if directive to provide a fallback content.
Example:
If isVisible is false, the second div will be rendered.
v-else-if
v-else-ifThe v-else-if directive, as the name suggests, serves as an "else if" block for v-if.
Example:
<div v-if="type === 'A'">Type A</div> <div v-else-if="type === 'B'">Type B</div> <div v-else>Other Type</div>
If type is 'B', the second div will be rendered.
v-show
v-showThe v-show directive toggles the visibility of an element based on the truthiness of an expression. Unlike v-if, v-show does not remove the element from the DOM; it just toggles the display CSS property.
Example:
If isVisible is true, the div will be displayed.
v-for
v-forThe v-for directive is used to render a list of items by iterating over an array or an object.
Example:
new Vue({
el: '#app',
data: {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
]
}
});This will render a list of items.
v-on
v-onThe v-on directive is used to listen to DOM events and execute some JavaScript when they are triggered.
Example:
When the button is clicked, the doSomething method will be called.
v-pre
v-preThe v-pre directive skips compilation for this element and all its children. This can be used to display raw mustache tags.
Example:
v-cloak
v-cloakThe v-cloak directive is used to keep the element and its children hidden until Vue's compilation is done. This is useful to prevent the flash of uncompiled mustache tags.
Example:
v-once
v-onceThe v-once directive renders the element and component once and skips future updates. This can be used to optimize performance.
Example:
Practical Exercise
Exercise 1: Using v-if and v-else
Create a simple Vue application that toggles the visibility of a message when a button is clicked.
HTML:
<div id="app"> <button v-on:click="toggleMessage">Toggle Message</button> <p v-if="isVisible">Hello, Vue.js!</p> <p v-else>Goodbye, Vue.js!</p> </div>
JavaScript:
new Vue({
el: '#app',
data: {
isVisible: true
},
methods: {
toggleMessage: function() {
this.isVisible = !this.isVisible;
}
}
});Solution:
When the button is clicked, the toggleMessage method toggles the isVisible data property, which in turn toggles the visibility of the message.
Exercise 2: Using v-for
Create a Vue application that displays a list of items and allows the user to add new items to the list.
HTML:
<div id="app">
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
<input v-model="newItemText" placeholder="Add a new item">
<button v-on:click="addItem">Add Item</button>
</div>JavaScript:
new Vue({
el: '#app',
data: {
items: [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' }
],
newItemText: ''
},
methods: {
addItem: function() {
if (this.newItemText.trim() !== '') {
this.items.push({ id: this.items.length + 1, text: this.newItemText });
this.newItemText = '';
}
}
}
});Solution:
When the "Add Item" button is clicked, the addItem method adds a new item to the items array, and the input field is cleared.
Conclusion
In this section, we covered the most commonly used built-in directives in Vue.js, including v-bind, v-model, v-if, v-else, v-else-if, v-show, v-for, v-on, v-pre, v-cloak, and v-once. These directives provide powerful ways to manipulate the DOM and create dynamic, interactive applications. By practicing with the provided exercises, you should now have a solid understanding of how to use these directives in your Vue.js projects.
Vue.js Course
Module 1: Introduction to Vue.js
- What is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance
Module 2: Vue.js Basics
- Template Syntax
- Data Binding
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- Slots
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
Module 5: State Management with Vuex
- Introduction to Vuex
- State, Getters, Mutations, and Actions
- Modules in Vuex
- Using Vuex in Components
- Advanced Vuex Patterns
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
Module 9: Advanced Vue.js Concepts
- Render Functions and JSX
- Server-Side Rendering (SSR) with Nuxt.js
- Vue 3 Composition API
- Performance Optimization
