Vue is declarative: you describe what should be displayed according to the state, and Vue takes care of the DOM. That is almost always what you want, but there are tasks that cannot be expressed as "state": moving the focus to a field, measuring an element's size, scrolling the page to a card or handing an element over to an external library. For these cases, Vue offers template refs, which give direct access to a DOM element or to a child component's instance. The second half of the lesson solves a mystery from the previous one: why type, disabled or @click reach BaseButton's inner <button> without being declared, and why the same thing did not happen in TextField. These are fallthrough attributes. With both tools, Colmena's booking form will move the focus to the first field with an error when it is submitted, TextField will forward attributes and events to its <input>, and BookingForm will expose a reset() method for its parent.
Contents
- When it is legitimate to touch the DOM
- Template refs with
useTemplateRef - The classic way: a
refwith the same name - When a ref is available
- Refs inside
v-for - Refs to child components and
defineExpose - Fallthrough attributes: what they are and how they are merged
inheritAttrs: false,$attrsanduseAttrs- Components with several root nodes
- Case study: focus on the first error, forwarded attributes and
reset()
- When it is legitimate to touch the DOM
Before learning how to access the DOM, it is worth being clear about when not to do it. If what you want to change can be expressed as state, do it with state:
| You want to... | Declarative way (correct) | Direct DOM access (avoid) |
|---|---|---|
| Change a text | {{ message }} |
element.textContent = ... |
| Add or remove a class | :class="{ active: ... }" |
element.classList.add(...) |
| Show or hide | v-if / v-show |
element.style.display = 'none' |
| Read what has been typed in a field | v-model |
element.value |
If you manually modify something that Vue manages, Vue will overwrite it on the next render or, worse, the DOM and the state will no longer match. By contrast, it is legitimate to access the DOM to:
- Manage focus:
element.focus()(there is no equivalent reactive attribute). - Measure: size and position (
getBoundingClientRect()), for example to position a menu. - Scroll:
scrollIntoView(),scrollTop. - Control media:
video.play(),audio.pause(). - Integrate non-Vue libraries: maps, charts, rich text editors, which need an element to mount themselves on.
- Select text:
input.select().
These are imperative operations by nature. In Reactivity: ref and reactive we used document.querySelector for an example of this kind; template refs are the idiomatic and safe way of doing it, because they point exactly to the element in this instance of the component, even if there are several on the page.
- Template refs with
useTemplateRef
useTemplateRefA template ref is a special attribute, ref, that gives an element a name:
<script setup>
import { useTemplateRef, onMounted } from 'vue'
// Gets the reference to the element whose ref attribute is 'search-input'
const searchField = useTemplateRef('search-input')
onMounted(() => {
searchField.value.focus() // the real DOM <input>
})
</script>
<template>
<input ref="search-input" type="search" />
</template>ref="search-input"in the template marks the element with a name.useTemplateRef('search-input')(Vue 3.5) returns a read-only ref whose.valuewill be the DOM element with that name.- The attribute's name is a string, and the variable can be called something else (
searchField). In this course we will use different names, or kebab-case ones, so that it is clear which is which.
- The classic way: a
ref with the same name
ref with the same nameBefore Vue 3.5 (and in a great deal of current code), you declared a ref(null) with exactly the same name as the ref attribute:
<script setup>
import { ref, onMounted } from 'vue'
const searchInput = ref(null) // same name as ref="searchInput"
onMounted(() => {
searchInput.value.focus()
})
</script>
<template>
<input ref="searchInput" type="search" />
</template>Vue sees that there is a script variable with the same name as the attribute and assigns the element to it. It works, but it is implicit: someone reading const searchInput = ref(null) does not know it is a template ref until they look in the template, and if you change the name in one place and not the other, the connection breaks without any errors.
useTemplateRef('name') |
ref(null) with the same name |
Options API | |
|---|---|---|---|
| Version | Vue 3.5+ | Vue 3.0+ | Vue 2 and 3 |
| Connection with the template | Explicit, by string | Implicit, by variable name | this.$refs.name |
| Variable name | Free | Must match | — |
| Read-only | Yes: you cannot assign it by mistake | No | — |
In new code, use useTemplateRef.
- When a ref is available
The element does not exist until the component is mounted. While <script setup> is running, the ref is null:
const searchField = useTemplateRef('search-input')
console.log(searchField.value) // null: the DOM does not exist yet
onMounted(() => {
console.log(searchField.value) // <input type="search">
})Remember the lifecycle you saw in Understanding the Vue Instance: Application, Components and Lifecycle: onMounted is the first moment at which the component's DOM is available. In addition:
- If the element is inside a
v-if, the ref goes back tonullwhen the condition is false, and receives the new element when it becomes true again. To react to that, you can watch it:watch(searchField, (element) => { if (element) element.focus() }). - If you change the state and want to act on the resulting DOM (for example, to focus a field that has just appeared), wait for Vue to update it with
await nextTick(), which you saw in 02-02. - In event handlers (a click, a submission), the component is already mounted: the ref is available, unless the element is hidden with
v-if.
- Refs inside
v-for
v-forIf the ref attribute is on an element that is repeated with v-for, the ref contains an array with all the elements:
<script setup>
import { useTemplateRef } from 'vue'
const { rooms } = defineProps({ rooms: { type: Array, required: true } })
const roomItems = useTemplateRef('room-items')
function scrollToRoom(id) {
// We search by a data-* attribute, because the order of the array is NOT guaranteed
const element = roomItems.value.find((el) => el.dataset.roomId === id)
element?.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
</script>
<template>
<ul>
<li v-for="room in rooms" :key="room.id" ref="room-items" :data-room-id="room.id">
{{ room.name }}
</li>
</ul>
</template>- The array is filled after mounting and is updated when the list changes.
- The order of the array does not necessarily match that of the data. That is why we identify each element with a
data-room-idinstead of using its position.
When you need more control (for example, to store the elements in an object by id), you can use a function ref: :ref="(el) => { if (el) items[room.id] = el }". Vue calls the function with the element when it is mounted and with null when it is unmounted.
- Refs to child components and
defineExpose
defineExposeIf you put ref on a component, you get its instance, not a DOM element. But components with <script setup> are closed by default: nothing they declare can be seen from the outside. The child decides what to make public with the defineExpose macro:
<!-- Child: TextField.vue (excerpt) -->
<script setup>
import { useTemplateRef } from 'vue'
const inputElement = useTemplateRef('input')
function focusField() {
inputElement.value?.focus()
}
defineExpose({ focusField }) // only this will be visible from the outside
</script>
<template>
<input ref="input" />
</template><!-- Parent -->
<script setup>
import { useTemplateRef } from 'vue'
import TextField from './base/TextField.vue'
const memberField = useTemplateRef('member-field')
function start() {
memberField.value.focusField() // calls the exposed method
}
</script>
<template>
<TextField ref="member-field" label="Name" />
</template>- Whatever is not exposed is inaccessible:
memberField.value.inputElementisundefined. This protects encapsulation: the parent depends only on what the child has decided to offer. - With the Options API, on the other hand, the whole instance is accessible (
this.$refs.field.anything), unless the component declares theexpose: ['focusField']option.
An important warning: calling a child's methods is imperative communication, and it should be the exception. If you can express it with props and events, do so. defineExpose is justified for actions that are not state: focusing, resetting, scrolling, playing. If you find yourself exposing data for the parent to read, it should probably be an event or a v-model.
- Fallthrough attributes: what they are and how they are merged
A fallthrough attribute is any attribute or event listener that the parent puts on a component and that the component does not declare as a prop or as an event. The most common cases are class, style, id, type, disabled, placeholder, aria-* and data-* attributes, and v-on listeners such as @click or @focus.
When the component has a single root element, Vue automatically adds those attributes to that element. This is what happens in BaseButton, whose root is the <button>:
<!-- Parent -->
<BaseButton
variant="secondary"
class="button--help"
type="submit"
aria-label="Open help"
@click="open"
@focus="logFocus"
>
?
</BaseButton><!-- Result in the DOM -->
<button type="submit" class="button button--secondary button--help" aria-label="Open help">?</button>
<!-- + click and focus listeners on the <button> -->variantdoes not appear in the DOM: it is a declared prop, so the component consumes it.- Everything else goes to the
<button>.
flowchart LR
P["Attributes on <BaseButton>"] --> D{"Declared as<br/>a prop or event?"}
D -->|"Yes"| C["Consumed by the component<br/>(variant)"]
D -->|"No"| R["Applied to the root element<br/>(class, type, aria-label, @click...)"]
When the root element already has that same attribute, Vue merges them according to these rules:
| Attribute | Rule | Example |
|---|---|---|
class |
The child's and the parent's classes are added together | button button--secondary + button--help |
style |
They are combined; if a property is repeated, the parent's wins | The parent's color over the child's |
Listeners (@click...) |
Both run: the child's and the parent's | The child logs and the parent reacts |
Anything else (type, id...) |
The parent's wins | type="submit" replaces type="button" |
The last rule explains why BaseButton can declare type="button" as a safe default and, even so, the booking form can turn it into type="submit".
And here is a consequence of declaring events that we announced in Props and Custom Events: if a component declares an event in defineEmits, for example click, the parent's @click is no longer a fallthrough listener: it will only run when the component calls emit('click'). It is another reason not to reuse native event names for your own events, unless you do so deliberately.
Finally, inheritance works in a chain: if a component's root element is another component, the fallthrough attributes pass to that component, which in turn applies them to its own root.
inheritAttrs: false, $attrs and useAttrs
inheritAttrs: false, $attrs and useAttrsSometimes the root element is not the right destination. That is the case with TextField: its root is a <div class="field">, but type, placeholder, min or @blur should go to the <input> inside it. That is why, in v-model on Your Own Components, we had to add the inputType prop and declare the blur event by hand.
The solution has two steps:
1. Turn off automatic inheritance with the inheritAttrs: false option. In <script setup> it is declared with the defineOptions macro (Vue 3.3+), which is used for component options that do not have a macro of their own:
2. Apply the attributes wherever you want with v-bind="$attrs". $attrs is an object with all the fallthrough attributes:
<template>
<div class="field">
<label :for="id">{{ label }}</label>
<input v-bind="$attrs" :id v-model="model" />
</div>
</template>Details about $attrs that you need to know:
- It includes
classandstyle(in Vue 2 it did not). WithinheritAttrs: false, they too go wherever you putv-bind="$attrs". If you prefer the class to go on the container and the rest on the control, you can split them up::class="$attrs.class"on the<div>and the rest, filtered, on the<input>. - Listeners appear as
onXxxproperties: the parent's@bluris in$attrs.onBlur. That is whyv-bind="$attrs"applies them too. - Order matters: on the same element, if
v-bind="$attrs"comes before one of the component's own attributes (:id), the component's own wins; if it comes after, the one from$attrswins. Putv-bind="$attrs"first when the component must have the last word.
In the script, the same object is obtained with useAttrs():
import { useAttrs } from 'vue'
const attrs = useAttrs()
function describedBy() {
return attrs['aria-describedby'] // e.g. the id of a hint added by the parent
}Like the slots object, attrs is not reactive: read it in the template or in functions called during rendering, not in a computed or a watch.
- Components with several root nodes
A component with several root elements (a fragment) cannot know which one to apply the fallthrough attributes to, so it applies them to none and, if the parent passes any, it warns you. This is the case with ShortcutsHelp, which has two roots: the button and the paragraph. If you write <ShortcutsHelp class="floating-help" /> in App.vue, the console will show:
[Vue warn]: Extraneous non-props attributes (class) were passed to component but could not
be automatically inherited because component renders fragment or text or teleport root nodes.You have two solutions:
- Choose the destination explicitly with
v-bind="$attrs"on one of the root elements. The warning disappears because Vue sees that you have used$attrs. - Wrap the roots in a single element. This is the simplest option when the wrapper does not get in the way of the layout.
For ShortcutsHelp we will choose the wrapper: a <div class="help"> containing the button and the paragraph. That way the parent's attributes (a positioning class, an id) will be applied to the whole block.
- Case study: focus on the first error, forwarded attributes and
reset()
reset()10.1 TextField forwards attributes and exposes focusField()
Replace the <script setup> and the template of src/components/base/TextField.vue (the styles do not change):
<script setup>
import { useId, useTemplateRef, useAttrs } from 'vue'
// The parent's attributes will go to the <input>, not to the root <div>
defineOptions({ inheritAttrs: false })
const [model, modifiers] = defineModel({
type: [String, Number],
set(value) {
if (modifiers.uppercase && typeof value === 'string') {
return value.toUpperCase()
}
return value
}
})
// The temporary "inputType" prop disappears: type="..." is now enough
const { label, error = '' } = defineProps({
label: { type: String, required: true },
error: String
})
// defineEmits(['blur']) disappears too: @blur reaches the <input> via $attrs
const id = useId()
const errorId = `${id}-error`
const attrs = useAttrs()
// Combined aria-describedby: whatever the parent passes + our error message
function describedBy() {
const ids = [attrs['aria-describedby'], error ? errorId : null].filter(Boolean)
return ids.length > 0 ? ids.join(' ') : null
}
const inputElement = useTemplateRef('input')
function focusField() {
inputElement.value?.focus()
}
defineExpose({ focusField })
</script>
<template>
<div class="field">
<label :for="id">{{ label }}</label>
<input
v-bind="$attrs"
ref="input"
:id
v-model="model"
:aria-invalid="error ? 'true' : 'false'"
:aria-describedby="describedBy()"
/>
<p v-if="error" :id="errorId" class="error">{{ error }}</p>
</div>
</template>defineOptions({ inheritAttrs: false })+v-bind="$attrs"on the<input>:type,placeholder,autocomplete,min,max,readonly, thearia-*attributes and listeners such as@bluror@focusreach the control, which is where they make sense.v-bind="$attrs"comes first: if the parent tried to pass anid, ours would win, and ours is the one linked to the<label>. The same goes foraria-invalid.describedBy()does not overwrite the parent'saria-describedby: it combines it with the error's id (the attribute accepts several ids separated by spaces). It is a function called from the template, becauseattrsis not reactive.focusField()is the only public part of the component: the parent will be able to move the focus to the field without knowing its internal structure.
10.2 BaseButton already worked
BaseButton needs no changes: it has a single root element, the <button>, which is exactly where the attributes should go. That is why type="submit", :disabled, :aria-pressed, the button--help class and @click were already working in the previous lesson. You can check that it forwards @focus too:
<!-- Temporary test in any component -->
<BaseButton @focus="console.log('focus on the button')">Try</BaseButton>When you reach it with the Tab key, you will see the message: the listener has been applied to the inner <button>.
10.3 ShortcutsHelp with a single root
Wrap the template of ShortcutsHelp.vue:
<template>
<div class="help">
<!-- the BaseButton and the help paragraph, no changes -->
</div>
</template>10.4 BookingForm: attributes recovered
In 03-03 we lost some attributes when we switched to TextField. Now we can give them back and replace inputType with type. We also give each field a ref for the next section:
<!-- BookingForm.vue, in the template -->
<TextField
ref="member-field"
v-model.trim="form.member"
label="Member name"
autocomplete="name"
placeholder="e.g. Laura Gómez"
:error="visibleError('member')"
@blur="markTouched('member')"
/>
<TextField
ref="date-field"
v-model="form.date"
type="date"
:min="todayISO"
label="Date"
:error="visibleError('date')"
@blur="markTouched('date')"
/>
<TextField
ref="attendees-field"
v-model.number="form.attendees"
type="number"
min="1"
:max="formRoom.capacity"
label="Attendees"
:error="visibleError('attendees')"
@blur="markTouched('attendees')"
/>Also add ref="room-select" to the room <select>, ref="end-time-select" to the end time one, ref="notes-area" to the <textarea> and ref="rules-checkbox" to the rules checkbox. Inspect the attendees field with the browser's developer tools: the <input> now has type="number", min and max, and the <div class="field"> is clean.
10.5 Focus on the first field with an error
Until now, the "Book" button was disabled while there were errors. It is a common practice, but it has accessibility problems: a disabled button does not receive focus, many screen readers skip it and the user does not know what is missing. A better alternative is to leave the button always enabled and, if the user submits with errors, show them all and move the focus to the first invalid field. That is focus management: a legitimate case for accessing the DOM.
In the script of BookingForm.vue, add nextTick and useTemplateRef to the vue import and write, after the errors computed property:
// --- Refs to the fields, in the order in which they appear on screen ---
const fieldsInOrder = [
['member', useTemplateRef('member-field')],
['roomId', useTemplateRef('room-select')],
['date', useTemplateRef('date-field')],
['endTime', useTemplateRef('end-time-select')],
['attendees', useTemplateRef('attendees-field')],
['notes', useTemplateRef('notes-area')],
['acceptsRules', useTemplateRef('rules-checkbox')]
]
async function focusFirstError() {
await nextTick() // wait for the messages and the aria-describedby attributes to be rendered
const first = fieldsInOrder.find(([field]) => errors.value[field])
if (!first) return
const target = first[1].value
// TextFields expose focusField(); native elements have focus()
if (typeof target?.focusField === 'function') {
target.focusField()
} else {
target?.focus()
}
}And modify submitBooking:
function submitBooking() {
if (!formIsValid.value) {
// Show all the errors and take the user to the first one
for (const [field] of fieldsInOrder) {
touched[field] = true
}
focusFirstError()
return
}
const booking = {
// ... the same as before ...
}
emit('create', booking)
// The form is NO longer reset here: the parent will decide (section 10.6)
}In the template, remove :disabled="!formIsValid" from the submit BaseButton. The "N fields still need completing..." hint stays: it warns without blocking.
Let's analyse the decisions:
fieldsInOrderassociates each field with its ref. The order of the array is the visual one, from top to bottom: that way "the first error" is the one the user sees first.useTemplateRefis called directly at the top level of the script (inside the array), which is where these functions must be called.await nextTick(): when the fields are marked as touched, Vue has not yet rendered the error messages. If we focused immediately, the screen reader would read the field without its message, becausearia-describedbywould not yet point to it. AfternextTick, the DOM is up to date.- The target can be of two kinds: a
TextFieldinstance (which exposesfocusField()) or a native element (<select>,<textarea>,<input type="checkbox">, which havefocus()). We check which one it is withtypeof. - In Custom Directives we will see another way of managing focus: a reusable
v-focusdirective applied to an element from the template.
10.6 reset(): the parent decides when to start again
Why have we removed the reset from submitBooking? Because the form does not know whether the booking has been saved. Today App simply adds it to a list, but in module 5 it will be sent to the simulated API, which can fail; if it fails, the user should not lose what they have typed. The one that knows whether the operation went well is the parent, so it is the parent that must order the reset. It is an action, not data: a good case for defineExpose.
At the end of the script of BookingForm.vue:
The form's own "Reset" button still calls resetForm; from the outside, the same method is seen as reset.
In App.vue, add useTemplateRef to the vue import and:
const bookingForm = useTemplateRef('booking-form')
function recordBooking(booking) {
bookings.value.push(booking)
console.log('[Colmena] Booking created:', booking)
bookingForm.value.reset() // only after it has been saved successfully
}<BookingForm
ref="booking-form"
:room-id="selectedRoomId"
:attendees="requestedAttendees"
@create="recordBooking"
/>10.7 Try it
- With the form empty, click "Book": all the errors appear and the focus jumps to the name field. Fill it in and submit again: the focus goes to the date. Carry on like this until the booking is created.
- With a screen reader, check that, when the focus jumps, the field's label and its error message are read out.
- Inspect the name
<input>: it hasautocomplete="name", theplaceholderand a generatedid. The<div class="field">has no extra attributes. - Create a valid booking: it appears in the list and the form is reset, now on
App's orders. Temporarily comment out thebookingForm.value.reset()line: the booking is created, but the form keeps its data. Re-enable it. - Temporarily add
console.log(bookingForm.value)torecordBookingand create a booking: in the console you will see that, from the outside, the form's instance only offersreset(plus a few public Vue properties, such as$el). Try readingbookingForm.value.formorbookingForm.value.errors: they areundefined.
Common Mistakes and Tips
- Accessing a template ref before mounting. In
<script setup>it isnull; useonMounted, an event handler ornextTick. - Forgetting
nextTickafter changing the state. The DOM still reflects the previous state. - Relying on the order of the refs array in a
v-for. It is not guaranteed; identify the elements with adata-*attribute. - Using refs for what state can do. Changing texts, classes or visibility by hand breaks the synchronisation with Vue.
- Exposing data with
defineExposefor the parent to read. Use events orv-model; expose only actions. - Forgetting that
$attrsincludesclassandstyle. WithinheritAttrs: false, they too stop going to the root. - Accidentally placing
v-bind="$attrs"after the component's own attributes. The parent could overwrite an essentialidoraria-*attribute. - Ignoring the warning about non-inherited attributes in components with several roots. The attributes are lost silently.
- Tip: in generic components that wrap a control (
TextField, a select, a switch), always useinheritAttrs: false+v-bind="$attrs"on the control. That way they will work with any present or future HTML attribute without declaring a prop for each one.
Exercises
Exercise 1. Make the focus go to RoomFilters' search field when the application is mounted, but only on wide screens (for example, window.matchMedia('(min-width: 800px)').matches), because on mobile devices it would open the keyboard without the user asking for it.
Exercise 2. Add an exposed scrollToRoom(id) method to RoomList that smoothly scrolls to that room's <li>. Use it from App.vue so that, when the user changes the room in the form's <select>, that room becomes selected and the catalogue scrolls to its card. Hint: BookingForm will have to emit a new event when form.roomId changes.
Exercise 3. This BaseSwitch.vue component is used like this: <BaseSwitch v-model="showClock" class="switch--large" aria-label="Show clock" @change="logAction" />. Where does each attribute end up, and what is the problem? Fix it so that aria-label and @change go to the <input> and the class to the <label>.
<script setup>
const checked = defineModel({ type: Boolean, default: false })
</script>
<template>
<label class="switch">
<input v-model="checked" type="checkbox" role="switch" />
<span class="switch__track"></span>
</label>
</template>Solutions
Solution 1. In RoomFilters.vue:
import { ref, watch, onMounted, useTemplateRef } from 'vue'
const searchField = useTemplateRef('search-input')
onMounted(() => {
if (window.matchMedia('(min-width: 800px)').matches) {
searchField.value.focus()
}
})onMounted guarantees that the <input> exists. The media query is evaluated once, on mounting; it does not need to be reactive, because we are only deciding the initial focus.
Solution 2.
// RoomList.vue
import { useTemplateRef } from 'vue'
const roomItems = useTemplateRef('room-items')
function scrollToRoom(id) {
const element = roomItems.value?.find((el) => el.dataset.roomId === id)
element?.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
defineExpose({ scrollToRoom })<!-- RoomList.vue -->
<li v-for="room in rooms" :key="room.id" ref="room-items" :data-room-id="room.id">// BookingForm.vue: add 'changeRoom' to defineEmits and watch the field
watch(
() => form.roomId,
(id) => emit('changeRoom', id)
)// App.vue
const roomList = useTemplateRef('room-list')
function goToRoom(id) {
selectRoom(id)
roomList.value?.scrollToRoom(id)
}<RoomList ref="room-list" :rooms="visibleRooms">...</RoomList>
<BookingForm ... @change-room="goToRoom" />The ?. protects against two cases: the list not being mounted (for example, if the catalogue is showing the error state) and the room not being among those visible through the filters. Notice how the work is divided: the selection travels as state (event → App → prop), and the scrolling, which is an action on the DOM, as an exposed method.
Solution 3. With a single root element (<label>), all the fallthrough attributes end up on the <label>: the class is fine, but aria-label on the <label> does not name the control, and @change is registered on the <label>. In this particular case the <input>'s change event bubbles up to the <label> and the listener would actually run, but by chance; other events that do not bubble, such as focus or blur, would never arrive. The fix:
<script setup>
import { useAttrs } from 'vue'
defineOptions({ inheritAttrs: false })
const checked = defineModel({ type: Boolean, default: false })
const attrs = useAttrs()
// Everything except class and style, which stay on the <label>
function controlAttributes() {
const { class: _class, style: _style, ...rest } = attrs
return rest
}
</script>
<template>
<label class="switch" :class="$attrs.class" :style="$attrs.style">
<input v-bind="controlAttributes()" v-model="checked" type="checkbox" role="switch" />
<span class="switch__track"></span>
</label>
</template>inheritAttrs: false turns off automatic inheritance; the class and the style are applied to the <label> (for the layout) and the rest of the attributes and listeners (aria-label, onChange) to the <input> (for behaviour and accessibility). Destructuring with a "rest" element (...rest) separates the two groups.
Conclusion
Template refs give direct access to DOM elements or component instances: they are marked with ref="name" and obtained with useTemplateRef('name') (or, in code from before 3.5, with a ref(null) of the same name), they are available from onMounted, they become arrays inside v-for and, on a component with <script setup>, they only show what it publishes with defineExpose. They are for imperative operations (focus, measurements, scrolling, external libraries), never a substitute for state. Fallthrough attributes are the undeclared attributes and listeners that Vue applies to the root element, merging class, style and listeners and giving the parent priority for the rest; with inheritAttrs: false and v-bind="$attrs" (or useAttrs()) they are redirected to wherever they belong, and in components with several roots this has to be done explicitly. Colmena has gained a more accessible form, which focuses the first field with an error on submission; TextField forwards type, placeholder, aria-* attributes and listeners to its <input> without patches; ShortcutsHelp has a single root; and BookingForm exposes reset(), which App calls only once the booking has been saved.
Until now, each component always appears in the same place on the page and all its code is downloaded when the application opens. But the catalogue could be displayed in several ways (as a grid, as a table or on the building map), and some of those views may be heavy. In Dynamic and Async Components we will learn how to choose which component is rendered at runtime, how to preserve its state when switching from one to another and how to load components only when they are needed.
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: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
