Vue.js Directives – Complete Guide
Directives in Vue.js are special attributes prefixed with v- that provide reactive behavior to the DOM. They are a core feature of Vue that allow you to control visibility, rendering, loops, event handling, and more, all in a declarative way.
1. v-if and v-else
The v-if directive conditionally renders elements based on a boolean expression. You can also use v-else to define an alternative.
2. v-show
Unlike v-if, which adds or removes elements from the DOM, v-showonly toggles the display CSS property. This is useful for frequent toggling.
3. v-for
The v-for directive allows you to render lists dynamically. It works with arrays or objects.
4. v-on (Event Handling)
The v-on directive listens to DOM events such as clicks, input, or submit. The shorthand @ is commonly used.
5. v-model
v-model is a two-way binding directive, commonly used on form inputs to keep the data and the input in sync automatically.
6. v-bind
v-bind dynamically binds element attributes to data. Shorthand: :.
7. Custom Directives (v-my-directive)
Besides built-in directives, Vue allows you to create **custom directives** to encapsulate DOM behavior. For example, you could create a directive to auto-focus an input.
Conclusion
Vue directives provide a powerful and declarative way to manage the DOM. Mastering built-in directives like v-if, v-for, v-show, v-model, and v-bind is essential for building dynamic Vue applications. They reduce boilerplate code and make your applications easier to read and maintain.