YouTip LogoYouTip

Vue3 V Bind

## Vue.js 3 `v-bind` Directive The `v-bind` directive in Vue 3 is used to dynamically bind one or more attributes, or a component's props, to an expression. This ensures that when the underlying data changes, the bound HTML attributes or component properties update reactively. --- ## Overview and Syntax By default, HTML attributes are static strings. The `v-bind` directive instructs Vue to evaluate the attribute's value as a JavaScript expression rather than a literal string. ### Specifications * **Shorthand**: `:` or `.` (when using the `.prop` modifier) * **Same-name Shorthand**: `:attribute` can be shortened to just `:attribute` if the attribute name matches the variable name (introduced in Vue 3.4+). * **Expected Value Type**: `any` (when used with an argument) | `Object` (when used without an argument) * **Primary Use Case**: Dynamically binding HTML attributes, class lists, inline styles, or component props. --- ## Basic Usage ### Syntax Comparison ```html ``` ### Complete Example The following example demonstrates how to dynamically bind the `src` and `alt` attributes of an image element. Clicking the button toggles the image source reactively. ```html ``` --- ## Advanced Binding Scenarios ### 1. Dynamic Class Binding You can pass an object or an array to `:class` to dynamically toggle CSS classes based on your component's state. #### Object Syntax The class `active` will be applied if `isActive` evaluates to truthy: ```html
Dynamic Class Content
``` #### Array Syntax You can apply a list of classes dynamically: ```html
Array Class Content
``` --- ### 2. Dynamic Style Binding Inline styles can be bound using JavaScript object syntax. Property names can use either camelCase or kebab-case (wrapped in quotes). ```html
Styled Text Content
``` You can also bind directly to a style object in your data for cleaner templates: ```html ``` --- ### 3. Binding Multiple Attributes with an Object If you have an object containing multiple attribute-value pairs, you can bind them all to a single element by using `v-bind` without an argument. ```html ``` --- ## Key Considerations 1. **Boolean Attributes**: For boolean attributes like `disabled`, `readonly`, or `checked`, `v-bind` behaves slightly differently. If the bound value is a truthy value or an empty string (`""`), the attribute is included. If the value is falsy (e.g., `false`, `null`, or `undefined`), the attribute is omitted entirely from the rendered HTML element. 2. **CamelCase vs. Kebab-case**: When binding CSS properties in `:style`, Vue automatically handles vendor prefixing (e.g., `userSelect` will be compiled with appropriate browser prefixes if needed). 3. **Component Props**: When using `v-bind` on a custom component, it passes the data as a prop to the child component rather than rendering it as a standard HTML attribute.
← Vue3 V ElseVue3 Key β†’