Vue Directives
Directives are special attributes in Vue template syntax with the v- prefix. The responsibility of a directive is to apply behavior to the DOM when the value of its expression changes.
1. v-bind: Bind Attributes
Used to dynamically bind one or more HTML attributes.
- Shorthand:
:
2. v-on: Listen to Events
Used to listen to DOM events and execute some JavaScript code when the event is triggered.
-
Shorthand:
@
3. v-model: Two-Way Binding
v-model is a very powerful directive that creates two-way data binding on form <input>, <textarea>, and <select> elements. It automatically selects the correct way to update the element based on the control type.
v-model is essentially syntactic sugar, equivalent to combining v-bind:value and v-on:input.
4. v-if, v-else, v-else-if: Conditional Rendering
Used to conditionally render a block of content based on the truthiness of an expression. This block is only rendered when the directive's expression returns a truthy value.
The v-else element must immediately follow a v-if or v-else-if element, otherwise it will not be recognized.
5. v-show: Conditional Display
Another option for conditionally displaying elements is the v-show directive. Usage is similar:
The difference is that elements with v-show will always be rendered and retained in the DOM. v-show simply toggles the element's CSS display property.
v-ifvsv-show:v-ifis "true" conditional rendering because it ensures event listeners and child components inside the conditional block are properly destroyed and rebuilt during toggling.v-showhas higher overhead because it always renders the element regardless of initial conditions.- Choice: If you need to toggle frequently,
v-showis better. If conditions rarely change at runtime,v-ifis better.
6. v-for: List Rendering
Used to render a list based on an array. The v-for directive requires special syntax in the form (item, index) in items.
v-for can also be used to iterate over an object's properties.
Importance of :key: key is a special attribute that Vue uses to track the identity of each node, thereby reusing and reordering existing elements. The value of key must be a unique string or number.