new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vue · all subjects

template syntax & directives

51 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

JavaScript expressions in Vue templates

Vue supports the full power of JavaScript expressions in data bindings, including arithmetic operations, ternary operators, method calls, and template literals. Expressions can be used inside text interpolations and in the attribute values of any Vue directive.

v-on directive shorthand

The v-on directive has a shorthand using the @ character. For example, @click="doSomething" is shorthand for v-on:click="doSomething".

Directive modifiers

Modifiers are special postfixes denoted by a dot, which indicate that a directive should be bound in some special way. For example, the .prevent modifier tells the v-on directive to call event.preventDefault() on the triggered event.

In-DOM templates and uppercase attribute names

When using in-DOM templates (templates directly written in an HTML file), you should avoid naming dynamic argument keys with uppercase characters, as browsers will coerce attribute names into lowercase. Templates inside Single-File Components are not subject to this constraint.

Dynamic argument syntax constraints

Dynamic argument expressions have syntax constraints because certain characters, such as spaces and quotes, are invalid inside HTML attribute names. Complex dynamic arguments are better handled using computed properties instead of inline expressions.

Dynamic argument value must be string or null

Dynamic arguments are expected to evaluate to a string, with the exception of null. The special value null can be used to explicitly remove the binding. Any other non-string value will trigger a warning.

Dynamic directive arguments

You can use a JavaScript expression in a directive argument by wrapping it with square brackets. For example, v-bind:[attributeName]="url" will evaluate attributeName as a JavaScript expression and use its value as the final argument. This works with any directive that takes arguments.

Directive arguments

Some directives can take an argument, denoted by a colon after the directive name. For example, in v-bind:href, 'href' is the argument. In the shorthand syntax :href, the v-bind: part is condensed to a single colon.

What are directives

Directives are special attributes prefixed with v- that apply special reactive behavior to the rendered DOM. Directive attribute values are expected to be single JavaScript expressions, except for v-for, v-on, and v-slot which have special syntax.

Restricted globals access in template expressions

Template expressions are sandboxed and only have access to a restricted list of globals. Common built-in globals like Math and Date are exposed, but user-attached properties on window are not accessible. You can define additional globals for all Vue expressions by adding them to app.config.globalProperties.

Only expressions allowed, not statements

Each data binding can only contain a single expression, not a statement. Statements like variable declarations (var a = 1) or flow control (if statements) will not work. A simple check is whether the code could be used after the return keyword.

Functions in binding expressions should not have side effects

Functions called inside binding expressions will be called every time the component updates. Therefore, they should not have any side effects, such as changing data or triggering asynchronous operations.

Text interpolation with mustache syntax

The most basic form of data binding in Vue templates uses the mustache syntax with double curly braces, for example {{ msg }}. The content between the braces will be replaced with the value of the specified property from the component instance and will be updated whenever the property changes.

v-html directive for raw HTML output

To output real HTML instead of plain text, use the v-html directive. The v-html directive replaces the element's inner HTML with the value of the expression, which is interpreted as plain HTML. Data bindings inside v-html content are ignored. You cannot use v-html to compose template partials; components are the fundamental unit for UI reuse.

v-html security warning

Dynamically rendering arbitrary HTML with v-html can lead to XSS vulnerabilities. Only use v-html on trusted content and never on user-provided content.

v-bind directive for attribute bindings

Mustaches cannot be used inside HTML attributes. Use the v-bind directive to reactively bind an HTML attribute to a data property. For example, v-bind:id="dynamicId" will keep the element's id attribute in sync with the dynamicId property. If the bound value is null or undefined, the attribute will be removed from the rendered element.

v-bind shorthand syntax

The v-bind directive has a shorthand syntax using a colon. Instead of v-bind:id="dynamicId", you can write :id="dynamicId". The shorthand syntax is optional but commonly used.

Same-name shorthand for v-bind (Vue 3.4+)

In Vue 3.4 and above, if the attribute has the same name as the variable being bound, the syntax can be further shortened to omit the attribute value. For example, :id without a value is equivalent to :id="id", and v-bind:id also works the same way.

Boolean attributes with v-bind

When binding to boolean attributes like disabled, v-bind includes the attribute if the value is truthy or an empty string, and omits it for falsy values. This maintains consistency with HTML boolean attribute behavior.

Dynamically binding multiple attributes

You can use v-bind without an argument to bind all properties of a JavaScript object as attributes to a single element. For example, v-bind="objectOfAttrs" where objectOfAttrs is an object with attribute names as keys.

v-cloak hides un-compiled templates in no-build-step setups

v-cloak is only needed in no-build-step setups. It hides un-compiled templates until they are ready. When using in-DOM templates, there can be a 'flash of un-compiled templates' where the user sees raw mustache tags until the mounted component replaces them with rendered content. v-cloak remains on the element until the associated component instance is mounted. Combined with CSS rules like [v-cloak] { display: none }, it hides raw templates until the component is ready.

v-on examples

Examples of v-on usage: <button v-on:click="doThis"></button> for method handler, <button v-on:[event]="doThis"></button> for dynamic event, <button v-on:click="doThat('hello', $event)"></button> for inline statement, <button @click="doThis"></button> for shorthand, <button @[event]="doThis"></button> for shorthand dynamic event, <button @click.stop="doThis"></button> to stop propagation, <form @submit.prevent></form> to prevent default without expression, <button @click.stop.prevent="doThis"></button> to chain modifiers, <input @keyup.enter="onEnter" /> for key modifier, <button v-on:click.once="doThis"></button> to trigger at most once, <button v-on="{ mousedown: doThis, mouseup: doThat }"></button> for object syntax, <MyComponent @my-event="handleThis" /> for custom events on child component, <MyComponent @my-event="handleThis(123, $event)" /> for inline statement with custom events.

v-bind directive syntax and modifiers

v-bind dynamically binds one or more attributes or component props to an expression. Shorthand: : or . (when using .prop modifier). It can omit value when attribute and bound value have the same name (requires 3.4+). Expects any (with argument) or Object (without argument). Argument is 'attrOrProp' (optional). Modifiers: .camel (transform kebab-case attribute name to camelCase), .prop (force binding as DOM property, 3.2+), .attr (force binding as DOM attribute, 3.2+). v-bind supports additional value types like Array or Objects when binding class or style attributes. By default, Vue checks if the element has the key as a property using an 'in' operator check; if defined, it sets as DOM property instead of attribute. Use .prop or .attr modifiers to override. When used without argument, can bind an object of attribute name-value pairs. For component prop binding, the prop must be properly declared in the child component.

v-bind examples

Examples of v-bind usage: <img v-bind:src="imageSrc" /> to bind attribute, <button v-bind:[key]="value"></button> for dynamic attribute name, <img :src="imageSrc" /> shorthand, <img :src /> same-name shorthand (3.4+) expands to :src="src", <button :[key]="value"></button> shorthand dynamic attribute, <img :src="'/path/to/images/' + fileName" /> with string concatenation, <div :class="{ red: isRed }"></div> class binding with object, <div :class="[classA, classB]"></div> class binding with array, <div :class="[classA, { classB: isB, classC: isC }]"></div> class binding mixed, <div :style="{ fontSize: size + 'px' }"></div> style binding, <div :style="[styleObjectA, styleObjectB]"></div> style binding with array, <div v-bind="{ id: someProp, 'other-attr': otherProp }"></div> binding object of attributes, <MyComponent :prop="someThing" /> prop binding, <MyComponent v-bind="$props" /> pass down parent props, <svg><a :xlink:special="foo"></a></svg> XLink, <div :someProperty.prop="someObject"></div> or <div .someProperty="someObject"></div> .prop shorthand, <svg :view-box.camel="viewBox"></svg> .camel modifier.

v-model directive for two-way binding

v-model creates a two-way binding on a form input element or component. It expects a value that varies based on the form input element or component output. It is limited to <input>, <select>, <textarea>, and components. Modifiers: .lazy (listen to change events instead of input), .number (cast valid input string to numbers), .trim (trim input).

v-slot directive for slots

v-slot denotes named slots or scoped slots that expect to receive props. Shorthand is #. It expects a JavaScript expression valid in a function argument position, including destructuring support. The expression is optional - only needed if expecting props. Argument is slot name (optional, defaults to 'default'). Limited to <template> and components (for a lone default slot with props).

v-slot examples

Examples of v-slot usage: <BaseLayout><template v-slot:header>Header content</template><template v-slot:default>Default slot content</template><template v-slot:footer>Footer content</template></BaseLayout> for named slots, <InfiniteScroll><template v-slot:item="slotProps"><div class="item">{{ slotProps.item.text }}</div></template></InfiniteScroll> for named slot receiving props, <Mouse v-slot="{ x, y }">Mouse position: {{ x }}, {{ y }}</Mouse> for default slot receiving props with destructuring.

v-pre directive skips compilation

v-pre skips compilation for the element and all its children. It does not expect an expression. Inside the element with v-pre, all Vue template syntax is preserved and rendered as-is. The most common use case is displaying raw mustache tags.

v-once directive renders element once

v-once renders the element and component once only and skips future updates. It does not expect an expression. On subsequent re-renders, the element/component and all its children are treated as static content and skipped. This optimizes update performance.

v-once examples

Examples of v-once usage: <span v-once>This will never change: {{msg}}</span> for single element, <div v-once><h1>Comment</h1><p>{{msg}}</p></div> for element with children, <MyComponent v-once :comment="msg"></MyComponent> for component, <ul><li v-for="i in list" v-once>{{i}}</li></ul> with v-for directive.

v-memo directive memoizes template sub-trees (3.2+)

v-memo is only supported in 3.2+. It memoizes a sub-tree of the template and can be used on both elements and components. It expects a fixed-length array of dependency values to compare for memoization. If every value in the array is the same as last render, updates for the entire sub-tree are skipped. Even Virtual DOM VNode creation is skipped and the memoized copy of the sub-tree is reused. It is important to specify the memoization array correctly to avoid skipping necessary updates. v-memo with an empty dependency array (v-memo="[]") is functionally equivalent to v-once.

v-memo with v-for performance optimization

v-memo is provided for micro optimizations in performance-critical scenarios and should rarely be needed. The most common case is when rendering large v-for lists (where length > 1000). Example: <div v-for="item in list" :key="item.id" v-memo="[item.id === selected]"><p>ID: {{ item.id }} - selected: {{ item.id === selected }}</p><p>...more child nodes</p></div> allows unaffected items to reuse their previous VNode and skip diffing when selected state changes. Do not include item.id in the memo dependency array since Vue automatically infers it from the item's :key. When using v-memo with v-for, they must be on the same element; v-memo does not work inside v-for.

v-cloak example usage

v-cloak example: CSS rule [v-cloak] { display: none; } and HTML <div v-cloak>{{ message }}</div>. The <div> will not be visible until compilation is done.

v-text directive usage and behavior

v-text updates the element's textContent property by setting it to a string value. It will overwrite any existing content inside the element. If you need to update only part of the textContent, use mustache interpolations like <span>Keep this but update a {{dynamicPortion}}</span> instead.

v-html directive and security warning

v-html updates the element's innerHTML with a string value. Contents are inserted as plain HTML and Vue template syntax will not be processed. Dynamically rendering arbitrary HTML can lead to XSS attacks, so only use v-html on trusted content and never on user-provided content. In Single-File Components, scoped styles will not apply to content inside v-html because that HTML is not processed by Vue's template compiler; use CSS modules or an additional global <style> element with a manual scoping strategy like BEM instead.

v-show directive behavior

v-show toggles the element's visibility based on the truthy-ness of the expression value. It works by setting the display CSS property via inline styles and will try to respect the initial display value when the element is visible. It triggers transitions when its condition changes.

v-if directive behavior and priority over v-for

v-if conditionally renders an element or template fragment based on the truthy-ness of the expression value. When a v-if element is toggled, the element and its contained directives and components are destroyed and re-constructed. If the initial condition is falsy, the inner content won't be rendered at all. It can be used on <template> to denote a conditional block containing only text or multiple elements. v-if triggers transitions when its condition changes. When used together, v-if has a higher priority than v-for and using these two directives together on one element is not recommended.

v-else-if directive requirements

v-else-if denotes the 'else if block' for v-if and can be chained. It expects any truthy-ness expression. The restriction is that the previous sibling element must have v-if or v-else-if. It can be used on <template> to denote a conditional block containing only text or multiple elements.

v-for directive syntax and key binding

v-for renders the element or template block multiple times based on source data which can be Array, Object, number, string, or Iterable. The directive's value must use the special syntax 'alias in expression' to provide an alias for the current element being iterated. Syntax examples: <div v-for="item in items"></div> for arrays, <div v-for="(item, index) in items"></div> for index, <div v-for="(value, key) in object"></div> for object keys, <div v-for="(value, name, index) in object"></div> for both keys and index. The key special attribute provides an ordering hint: <div v-for="item in items" :key="item.id"></div>. v-for works on values implementing the Iterable Protocol, including native Map and Set.

v-on directive syntax and modifiers

v-on attaches an event listener to the element with shorthand @. It expects Function, Inline Statement, or Object (without argument). The argument is 'event' (optional if using Object syntax). Modifiers: .stop (call event.stopPropagation()), .prevent (call event.preventDefault()), .capture (add listener in capture mode), .self (only trigger if dispatched from this element), .{keyAlias} (only trigger on certain keys), .once (trigger at most once), .left (only for left button mouse events), .right (only for right button), .middle (only for middle button), .passive (attach with {passive: true}). The event type is denoted by the argument. When used on custom element components, it listens to custom events. The method receives the native event as the only argument, or inline statements have access to $event property. v-on supports binding to an object of event/listener pairs without an argument, but object syntax does not support modifiers.

<template> with v-for can have key attribute

A <template> with a `v-for` directive can have a `key` attribute. All other attributes and directives will be discarded, as they aren't meaningful without a corresponding element.

<template> special handling triggered by specific directives

The special handling for <template> is only triggered if it is used with one of these directives: `v-if`, `v-else-if`, `v-else`, `v-for`, or `v-slot`. If none of those directives are present, it will be rendered as a native <template> element instead.

<template> tag used as placeholder with built-in directives

The <template> tag is used as a placeholder when you want to use a built-in directive without rendering an element in the DOM. It is a built-in special element, not a true component, and is compiled away during template compilation.

key attribute uniqueness requirement

Children of the same common parent must have unique keys. Duplicate keys will cause render errors.

key attribute behavior with keys

With keys, Vue will reorder elements based on the order change of keys, and elements with keys that are no longer present will always be removed or destroyed.

key attribute with transition example

The key attribute can be used to force element replacement and trigger transitions: ```vue-html <transition> <span :key="text">{{ text }}</span> </transition> ``` When text changes, the span will always be replaced instead of patched, so a transition will be triggered.

key attribute purpose in virtual DOM

The key special attribute is primarily used as a hint for Vue's virtual DOM algorithm to identify vnodes when diffing the new list of nodes against the old list.

key attribute type and values

The key special attribute expects a value of type number, string, or symbol.

key attribute behavior without keys

Without keys, Vue uses an algorithm that minimizes element movement and tries to patch and reuse elements of the same type in-place as much as possible.

key attribute to force element replacement

The key attribute can be used to force replacement of an element or component instead of reusing it. This is useful when you want to properly trigger lifecycle hooks of a component or trigger transitions.

key attribute with v-for example

The most common use case for key is combined with v-for: ```vue-html <ul> <li v-for="item in items" :key="item.id">...</li> </ul> ```

Give your agent this brain