Connect interface templates to reactive state using Vue components.
Before starting: JavaScript functions, objects, modules, HTML, and CSS.
Practice project: Build an accessible course tracker with explicit loading and error states.
Foundations & Architecture
- Vue.js Introduction, Philosophy & Progressive Architecture
- Setting Up Vue with Vite, Create-Vue & CDN Options
Read the example and try it
Start the Vite development server from the project directory. Open the local URL printed by the server and change one template label.
Terminal with Node and npm. Choose a JavaScript Vue starter.
npm create vue@latest room-board cd room-board npm install npm run devCompare starting development with building output files.
In a Vue/Vite starter, run its dev script, stop it, then run its build script.
Expected result
Development serves a local URL. Production build writes dist/index.html and its referenced assets. Port, duration and hashed filenames vary. - Anatomy of a Single File Component (SFC: template, script, style)
Read the example and try it
A single-file component keeps the state and the template that reads it together. Save this example as a .vue component.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref } from 'vue' const seats = ref(4) </script> <template><p>Seats left: {{ seats }}</p></template>Identify markup, component logic and appearance in one component.
Use Room.vue with a template showing a button, a script setup counter, and a scoped style for the button.
Expected result
The template determines the markup, the script owns the reactive value, and the style changes presentation. Pressing the button increments the visible count. - Options API vs Composition API: Architectural Comparison
Read the example and try it
In the Options API, data returns fresh state per component instance. A method can update that instance through this.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script> export default { data() { return { seats: 4 } }, methods: { reserve() { if (this.seats > 0) this.seats-- } } } </script> <template><button @click="reserve">Seats left: {{ seats }}</button></template>Represent one counter using each API's state style.
Build two counters starting at 0; one uses data() and one uses ref(0). Click each once.
Expected result
Both display 1. Options code writes this.count; Composition script writes count.value. - Application Instances (createApp()), Mount & Global Configuration
Read the example and try it
Mount the app after the host element is available. Each app controls the DOM inside its own mount point.
Vue 3 project fragment. Use the template or setup block in a component, import the named Vue APIs, and supply the reactive values referenced by the example.
import { createApp } from 'vue' import Board from './Board.vue' createApp(Board).mount('#board')Create an app and identify the element it takes over.
Mount an app with template <p>Ready</p> into an existing #lab container.
Expected result
The container's text is Ready and its child is a P element.
Template Syntax & Directives
- Text Interpolation ({{ }}), Raw HTML (v-html) & Attributes
Read the example and try it
Interpolation displays a string as text. A label supplied by a student should never be interpreted as a template.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> const label = '<Gate A>' </script> <template><p>{{ label }}</p></template>Compare interpolation and v-html using a trusted sample tag.
Use the trusted constant <b>Lab</b> in one interpolation and one v-html binding.
Expected result
The first shows literal brackets and contains no b element. The second displays bold Lab and contains one b element. - Dynamic Attribute Binding (v-bind), Class & Style Object/Array Syntax
Read the example and try it
Bind a boolean property to an expression. The browser disables this button when the last seat has been booked.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref } from 'vue' const seats = ref(0) </script> <template> <button :disabled="seats === 0" :class="{ full: seats === 0 }">Reserve</button> </template>Toggle a reactive flag and inspect a button's disabled state.
Bind disabled to a ref initialized false, then change it to true.
Expected result
The button begins enabled and becomes disabled after Vue updates the DOM. - Conditional Rendering: v-if, v-else-if, v-else vs v-show
Read the example and try it
Conditional rendering creates the appropriate branch. With v-show a frequently toggled panel stays mounted and only its display changes.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref } from 'vue' const seats = ref(1) const helpOpen = ref(true) </script> <template> <p v-if="seats === 0">Full</p> <p v-else>{{ seats }} available</p> <aside v-show="helpOpen">Choose a seat before booking.</aside> </template>Compare the lifetime of a child controlled by v-if and v-show.
Give each child an unmount hook and toggle its condition from true to false.
Expected result
The v-if child unmounts once. The v-show child stays mounted with display:none. Toggling back creates a fresh v-if child. - List Rendering with v-for, Array Detection & Mandatory :key
Read the example and try it
A stable key ties each row to a particular record. Sorting the list can then move a row without confusing two input fields.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> const stops = [{id:7,name:'Hill'},{id:2,name:'Lake'}] </script> <template> <ul><li v-for="stop in stops" :key="stop.id">{{ stop.name }}</li></ul> </template>Reorder editable rows and check which input follows which record.
Key editable rows by stable IDs A and B. Type red in A, then reverse the order.
Expected result
The row order becomes B,A. A still owns red and its input node follows A. B does not inherit A's edit. - Event Handling (v-on, @), Inline Handlers & Event Modifiers (.prevent, .stop, .once, .enter)
Read the example and try it
Listen for the form submit event to support both clicks and Enter. The prevent modifier stops navigation while the component processes the input.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref } from 'vue' const count = ref(1) const message = ref('') function reserve() { message.value = Number.isInteger(count.value) && count.value > 0 ? 'Seats requested: ' + count.value : 'Enter a positive whole number' } </script> <template> <form @submit.prevent="reserve"><label>Seats <input v-model.number="count" type="number"></label><button>Reserve</button></form> <output>{{ message }}</output> </template>Handle a form submit without a browser navigation.
Dispatch a cancelable submit event on a form using @submit.prevent.
Expected result
The handler runs once and the submit event is marked defaultPrevented. The page does not navigate.
Modern Reactivity Core
- Reactivity Fundamentals: ref(), .value & Auto-Unwrapping in Templates
Read the example and try it
A ref has a value property in JavaScript. Templates unwrap a top-level ref automatically.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref } from 'vue' const seats = ref(3) function reserve() { if (seats.value > 0) seats.value-- } </script> <template> <button @click="reserve">Available: {{ seats }}</button> </template>Increment a ref in script and display it in a template.
Start count=2 and increment once in script.
Expected result
3 - reactive() with ES6 Proxies vs ref(): When to Use Which & Pitfalls
Read the example and try it
Read and write a reactive object's properties through the proxy. A copied primitive has no connection to later updates.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { reactive } from 'vue' const room = reactive({ seats: 4 }) const previous = room.seats room.seats-- console.log(previous, room.seats) </script> <template> <p>Before: {{ previous }}. Now: {{ room.seats }}.</p> </template>Update a proxy property and observe its binding.
Set reactive({seats:8}).seats to 5 after mount.
Expected result
Rendered value changes from 8 to 5. - Computed Properties (computed()): Reactive Caching vs Methods
Read the example and try it
A computed value derives the bill from its inputs. Vue can reuse the cached result until a reactive dependency changes.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref, computed } from 'vue' const qty = ref(2) const price = ref(4) const bill = computed(() => qty.value * price.value) </script> <template> <label>Seats <input type="number" v-model.number="qty"></label><p>Bill: {{ bill }}</p> </template>Count evaluations while reading the same computed total twice.
Create a computed that doubles ref(3) and increments a call counter in its getter. Read twice, update the input to 4, and read once.
Expected result
6, 6, 8; getter call count 2. - Writable Computed Properties with Custom Getters and Setters
Read the example and try it
A writable computed translates edits back into the source state. Here the source stays in minutes while the UI edits hours.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { computed, ref } from 'vue' const minutes = ref(90) const hours = computed({ get: () => minutes.value / 60, set: value => { minutes.value = value * 60 } }) </script> <template> <label>Hours <input type="number" v-model.number="hours"></label><p>{{ minutes }} minutes</p> </template>Map a combined name edit back to underlying state.
Use first=Ana and last=Lee. Assign "Bo Kim" through a writable computed full name for this two-word fixture.
Expected result
first becomes Bo, last becomes Kim, and reading full name returns Bo Kim. - Reactivity Utilities: toRefs(), toRef(), isRef(), and unref()
Read the example and try it
Keep a reactive connection when exposing a single property. Assigning through the ref changes the original room object.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { reactive, toRef } from 'vue' const room = reactive({ seats: 5 }) const count = toRef(room, 'seats') count.value-- console.log(room.seats) </script> <template> <p>Seats remaining: {{ room.seats }}</p> </template>Destructure a reactive count with and without a ref.
Copy count from reactive({count:1}) and also obtain a linked ref with toRefs. Set the property to 3.
Expected result
Plain copy 1; linked ref 3.
Watchers & Side Effects
- Watchers with watch(): Deep Watching, Immediate Execution & Sources
Read the example and try it
A watcher can react to changes in one chosen field. A getter supplies the current property value whenever Vue checks it.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { reactive, watch } from 'vue' const room = reactive({ label: 'East' }) watch(() => room.label, (next, previous) => console.log(previous, next)) </script> <template> <label>Room <input v-model="room.label"></label> </template>Trace two searches that finish in reverse order.
Start search A, then search B. Make B resolve first and A last. Register cleanup or a request-version check.
Expected result
The displayed result remains B after A finishes. An outdated completion must not overwrite B or clear B's loading state. - watchEffect() & watchPostEffect(): Automatic Dependency Tracking
Read the example and try it
An effect tracks the reactive values it reads while running. Changing the selected label updates the document title.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref, watchEffect } from 'vue' const label = ref('Lab') watchEffect(() => { document.title = 'Room ' + label.value }) </script> <template> <label>Room <input v-model="label"></label> </template>Change a read dependency and an unrelated one separately.
In a watchEffect increment a run counter and read only ref A. Change unrelated B, then A, awaiting nextTick after each.
Expected result
Counts are 1, 1, 2. - Stopping Watchers, Effect Invalidation & onCleanup()
Read the example and try it
Cleanup removes the old pending timer before another search starts. Stop the watcher when you no longer need changes.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref, watch } from 'vue' const query = ref('') const stop = watch(query, (value, old, cleanup) => { const timer = setTimeout(() => console.log('Search', value), 200) cleanup(() => clearTimeout(timer)) }) </script> <template> <label>Stop <input v-model="query"></label><button @click="stop()">Stop watching</button> </template>Stop one watcher and verify another can still react.
Create two non-immediate watchers on one ref. Stop A, change the value, await nextTick.
Expected result
A runs zero times and B runs once. - Two-Way Binding with v-model on Inputs, Checkboxes, Selects & Modifiers (.trim, .number, .lazy)
Read the example and try it
Two-way binding connects the input and component state. The trim modifier removes surrounding spaces from a learner's search term.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref } from 'vue' const query = ref('') </script> <template> <label>Find a room <input v-model.trim="query"></label> <p>Searching for {{ query }}</p> </template>Edit an input and update its model from a button.
Start the model at Lab. Type Hall in the input, then set the model to Gym using a button.
Expected result
After typing, the model is Hall. After the button update, the input's displayed value is Gym. - Custom Component v-model with Multiple Bindings and Custom Modifiers
Read the example and try it
A named model lets a parent bind one specific child value. In this Vue 3.4+ child component the model name is seat.
Child component in a Vue 3.4+ project. Save it in a .vue file and import it in the parent component.
<script setup> const seat = defineModel('seat', { type: Number, required: true }) </script> <template><input type="number" v-model.number="seat"></template>Trace an edited value from a child input back to its parent.
A child using modelValue emits update:modelValue with Hall. The parent starts with Lab and uses v-model.
Expected result
Parent state changes to Hall. The updated prop flows back to the child on the next render.
Component Deep Dive & Communication
- Component Props: defineProps(), Type Validation & Default Values
Read the example and try it
A prop declares what the parent passes to the child. Use a bound expression for a number when rendering the child.
Child component in a Vue 3.4+ project. Save it in a .vue file and import it in the parent component.
<script setup> defineProps({ seats: { type: Number, default: 0 } }) </script> <template><p>{{ seats }} free</p></template>Replace a direct prop assignment with a request to the parent.
Parent owns count=2. The child asks for an increment with emit instead of assigning its prop.
Expected result
After the parent handles the event its count and the child's displayed prop both read 3. - Custom Events: defineEmits(), Payload Validation & Event Handling
Read the example and try it
Emit a booking request with the seat ID. The parent can then decide whether it is still available.
Child component in a Vue 3.4+ project. Save it in a .vue file and import it in the parent component.
<script setup> const emit = defineEmits(['reserve']) </script> <template><button @click="emit('reserve', 7)">Request seat 7</button></template>Relay a child selection through an intermediate component.
Grandchild emits select with room 7. The intermediate component listens and emits select with the same payload.
Expected result
The top component receives 7 once. Removing the relay leaves the top listener uncalled. - Fallthrough Attributes, inheritAttrs: false & useAttrs()
Read the example and try it
Put inherited attributes on the actual control when a component has a wrapper. An id from the parent now targets the input.
Child component in a Vue 3.4+ project. Save it in a .vue file and import it in the parent component.
<script setup> defineOptions({ inheritAttrs: false }) </script> <template><label>Room <input v-bind="$attrs"></label></template>Choose where a wrapper should forward an external class.
Set inheritAttrs:false in a wrapper around an input and forward $attrs to the input. Pass class="highlight" to the wrapper.
Expected result
The input receives highlight. The outer wrapper does not acquire that class automatically. - Slots Architecture: Default Slots, Named Slots (#name) & Scoped Slots
Read the example and try it
Slots let callers supply content inside a shared frame. The default text appears only when a caller omits that slot.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<template> <article><header><slot name="title">Room details</slot></header><slot></slot></article> </template>Use a scoped slot prop alongside a parent variable.
A scoped slot supplies room=Lab and the parent owns prefix=North.
Expected result
The parent-authored slot displays North Lab by combining its own prefix with the child's slot prop. - Provide & Inject: Deep Dependency Injection without Prop Drilling
Read the example and try it
Provide a value from a common ancestor. A descendant can inject it without forcing intermediate components to declare forwarding props.
Vue 3 project fragment. Use the template or setup block in a component, import the named Vue APIs, and supply the reactive values referenced by the example.
// In the ancestor's setup provide('room-id', ref(7)) // In a descendant's setup const roomId = inject('room-id')Sketch a nested theme override with provide and inject.
The root provides theme=light. A nested section provides theme=dark under the same key.
Expected result
A descendant of that section injects dark. Its sibling under the root injects light.
Lifecycle Hooks & DOM Access
- Lifecycle Hooks: onMounted, onUpdated, onUnmounted, onBeforeMount
Read the example and try it
Release resources acquired by a component. Clearing the timer on unmount prevents duplicate clocks after navigation.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref, onMounted, onUnmounted } from 'vue' const now = ref(Date.now()) let timer onMounted(() => { timer = setInterval(() => { now.value = Date.now() }, 1000) }) onUnmounted(() => clearInterval(timer)) </script> <template> <p>{{ new Date(now).toLocaleTimeString() }}</p> </template>Pair a window listener with cleanup on unmount.
Mount a component with a resize listener. Dispatch resize, unmount, then dispatch resize again.
Expected result
Listener count is 1 after both events together. Removing the same handler on unmount prevents the second call. - Template Refs: Accessing Direct DOM Elements with useTemplateRef / ref
Read the example and try it
A DOM ref is filled after mounting. Pair the variable with the input's ref attribute before calling focus.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref, onMounted } from 'vue' const field = ref(null) onMounted(() => field.value?.focus()) </script> <template><input ref="field" aria-label="Room"></template>Focus an input only when its ref is available.
Render an input only if open is true. Focus it after setting open and awaiting nextTick.
Expected result
Before mount the ref can be null. After opening, document.activeElement is the input. After closing, the ref returns to null. - nextTick(): Microtask Queue & Scheduling Updates after Reactive Mutations
Read the example and try it
Vue groups DOM updates after a state mutation. Await the next tick before checking the rendered label.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref, nextTick } from 'vue' const seats = ref(4) const labelElement = ref(null) async function reserve() { if (seats.value === 0) return seats.value-- await nextTick() console.log(labelElement.value.textContent) } </script> <template> <p ref="labelElement">{{ seats }}</p><button @click="reserve">Reserve</button> </template>Update a count and compare DOM text before and after nextTick.
Render count=1, change it to 2 and read text before and after nextTick.
Expected result
1 then 2. State changes immediately, DOM rendering is batched. - Component Template Refs & Explicit Method Exposure with defineExpose()
Read the example and try it
Expose a small operation when a parent needs to control the child input. The parent can use a component ref to call this method.
Child component in a Vue 3.4+ project. Save it in a .vue file and import it in the parent component.
<script setup> import { ref } from 'vue' const input = ref(null) function focus() { input.value?.focus() } defineExpose({ focus }) </script> <template> <input ref="input" aria-label="Search rooms"> </template>Expose a focus method while keeping internal state private.
Expose focusInput from a script-setup child and keep its draft private.
Expected result
The parent ref can call focusInput and focus the child's input. The private draft is not part of the exposed API. - Asynchronous Components (defineAsyncComponent) & <Suspense> Boundaries
Read the example and try it
Load a heavy chart only when it is rendered. A loading component can display while the import resolves.
Vue 3 project fragment. Use the template or setup block in a component, import the named Vue APIs, and supply the reactive values referenced by the example.
const SeatChart = defineAsyncComponent({ loader: () => import('./SeatChart.vue'), loadingComponent: ChartLoading })Add a loading state for a component fetched later.
Use an async component whose loader remains pending long enough to show the placeholder; set delay:0 for this test.
Expected result
The loading label appears while pending. Resolving the loader replaces it with the room component. A rejected loader uses the error state if configured.
Reusability & Composables
- Custom Composables: Naming Conventions, Return Conventions & Encapsulation
Read the example and try it
A composable can return state and actions together. Calling the function twice creates independent counters.
Save this as useSeats.js in a Vue project. Import useSeats and call it inside a component setup block.
import { ref } from 'vue' export function useSeats(initial) { const left = ref(initial) function reserve() { if (left.value > 0) left.value-- } return { left, reserve } }Call a counter composable twice and inspect whether state is shared.
Define useCounter so it allocates a new ref(0) inside each call. Increment the first result only.
Expected result
1 0 — the two instances are independent. - Building Production Composables: useFetch, Loading & Error States
Read the example and try it
A failed request must also clear the loading indicator. Check the HTTP status before accepting the JSON.
Vue single-file component. Add rooms.json containing {"label":"East"} to the public directory and open the app at its root URL.
<script setup> import { ref } from 'vue' const room = ref(null), error = ref(null), loading = ref(false) async function loadRoom(url) { loading.value = true; error.value = null try { const r = await fetch(url); if (!r.ok) throw Error('Room unavailable'); room.value = await r.json() } catch (e) { error.value = e.message } finally { loading.value = false } } </script> <template> <button :disabled="loading" @click="loadRoom('./rooms.json')">Load room</button> <p v-if="loading">Loading</p><p v-else-if="error">{{ error }}</p><p v-else-if="room">{{ room.label }}</p> </template>Represent pending, successful and failed requests separately.
Try a pending request, a successful response containing Lab and a rejected request.
Expected result
Pending shows loading. Success clears loading and displays Lab. Failure clears loading and displays an error rather than a success label. - Custom Directives: Hook Lifecycles (mounted, updated) & DOM Manipulation
Read the example and try it
A custom directive is suitable for a reusable DOM operation. In script setup the vFocus variable is available as v-focus.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> const vFocus = { mounted: el => el.focus() } </script> <template><input v-focus aria-label="Find a room"></template>Implement focus-on-mount for an input.
Mount an input with a local directive whose mounted hook calls el.focus().
Expected result
After mount document.activeElement is the input. - Vue Plugins Architecture: app.use(), Global Properties & Extensibility
Read the example and try it
A plugin can provide one shared setting at installation time. Install it before mounting the app.
Vue 3 project fragment. Use the template or setup block in a component, import the named Vue APIs, and supply the reactive values referenced by the example.
const roomsPlugin = { install(app, options) { app.provide('siteName', options.name) } } app.use(roomsPlugin, { name: 'Class timetable' })Register a plugin before mounting the app.
Install a plugin providing room=Lab before mounting a component that injects room.
Expected result
Lab - Styling Techniques: Scoped CSS, CSS Modules & Reactive CSS v-bind() in <style>
Read the example and try it
Scoped styles apply to markup owned by the component. A reactive CSS binding updates the colour when the severity changes.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> const colour = '#12643a' </script> <template><p class="status">Open</p></template> <style scoped>.status { color: v-bind(colour) }</style>Inspect a generated scoped selector and a component root.
Compile a component with scoped CSS .label {color:blue}. Inspect its matching DOM element.
Expected result
The generated rule and element share a generated data-v-* attribute. The suffix depends on the build. Parent scoped styles can also affect a child component's root.
Built-in Components & Animation
- <Transition> Component: Enter/Leave Classes & Keyframe Animation
Read the example and try it
The transition name connects state changes with CSS classes. Reduced-motion users can receive the same panel without a fade.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref } from 'vue' const open = ref(true) </script> <template> <button @click="open = !open">Toggle room</button> <Transition name="fade"><p v-if="open">Room available</p></Transition> </template> <style> .fade-enter-active,.fade-leave-active { transition: opacity .16s } .fade-enter-from,.fade-leave-to { opacity: 0 } @media (prefers-reduced-motion: reduce) { .fade-enter-active,.fade-leave-active { transition: none } } </style>Toggle a panel and distinguish the entering and leaving classes.
Set transition name="room" and toggle a panel with a nonzero CSS duration.
Expected result
During entry, room-enter-from and room-enter-active appear, then room-enter-to. During exit the leave classes appear. The transient classes disappear when complete. - <TransitionGroup>: Moving List Items, FLIP Animations & Coordinates
Read the example and try it
Give each moved item a stable key. The move class animates changes in position when the data order changes.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref } from 'vue' const pupils = ref([{id:4,name:'Mira'},{id:8,name:'Kay'}]) </script> <template> <button @click="pupils.reverse()">Reverse order</button> <TransitionGroup name="rank" tag="ol"> <li v-for="p in pupils" :key="p.id">{{ p.name }}</li> </TransitionGroup> </template> <style>@media (prefers-reduced-motion: no-preference) { .rank-move { transition: transform .2s } }</style>Move one item and remove another in a keyed list.
Start with keyed items A,B,C, reorder to C,A,B and then remove A.
Expected result
Final DOM order C,B. C and B retain their identities; A leaves. Movement animation additionally needs appropriate CSS. - Dynamic Components (<component :is="...">) & Caching with <KeepAlive>
Read the example and try it
KeepAlive caches component instances when switching views. Returning to the editor can restore the draft held in its local state.
Vue 3 project fragment. Use the template or setup block in a component, import the named Vue APIs, and supply the reactive values referenced by the example.
<KeepAlive><component :is="activeView" /></KeepAlive>Switch between two components and check an edited input on return.
Within KeepAlive, type draft in view A, switch to B, then back to A without eviction.
Expected result
A still shows draft; its cached instance was reactivated. An uncached remount would reset local state. - <Teleport>: Rendering Modals, Tooltips & Popovers to body or Target Nodes
Read the example and try it
Teleport changes where markup appears in the DOM. The message still reads data from the component that declared it.
Vue 3 single-file component. Save this as App.vue in a Vue project and start its development server.
<script setup> import { ref } from 'vue' const notice = ref('Seat reserved') </script> <template> <Teleport to="body"><p v-if="notice" role="status">{{ notice }}</p></Teleport> </template>Render a dialog elsewhere in the DOM while passing a parent prop.
Create target #portal outside #lab. Teleport a dialog displaying prop room=Hall to #portal.
Expected result
Hall appears inside #portal. The component still receives the parent prop even though its DOM is elsewhere. - Error Handling: onErrorCaptured & Global app.config.errorHandler
Read the example and try it
A parent can provide a fallback for a failed child. Switch to a safe rendering branch to avoid repeatedly rendering the broken child.
Vue 3 project fragment. Use the template or setup block in a component, import the named Vue APIs, and supply the reactive values referenced by the example.
const failed = ref(false) onErrorCaptured(() => { failed.value = true; return false })Show a fallback when a descendant render fails.
Throw a deliberate error from a descendant's render and let a boundary switch to fallback text.
Expected result
Fallback appears once and the broken child is no longer rendered. Avoid rendering the same failing subtree in the fallback.
Routing with Vue Router 4
- Vue Router 4 Fundamentals: createRouter, RouterView & RouterLink
Read the example and try it
The router matches paths to components. Install it on the app and place RouterView where the matched component should appear.
Vue Router 4 setup. Import createRouter, createWebHistory and the RoomList component.
const router = createRouter({ history: createWebHistory(), routes: [{ path: '/rooms', component: RoomList }] }) app.use(router)Map two paths to distinct page components.
Routes /rooms and /about display headings Rooms and About.
Expected result
Navigating to each path puts the matching heading in RouterView; only the active route's page is shown in that outlet. - Dynamic Route Matching, Route Parameters ($route.params), Props & Wildcards
Read the example and try it
A route parameter starts as text. Passing it as a prop makes the dependency visible in the detail component.
Vue 3 project fragment. Use the template or setup block in a component, import the named Vue APIs, and supply the reactive values referenced by the example.
const route = { path: '/rooms/:id', component: RoomDetail, props: true }Navigate between two IDs and update the displayed record.
Navigate from /rooms/1 to /rooms/2 using the same component and watch its ID parameter.
Expected result
The component displays room 2 after navigation. It cannot rely only on its initial mounted hook to refresh. - Nested Routes, Layout Patterns & Multi-Level <RouterView>
Read the example and try it
A child route renders inside the parent's RouterView. A relative child path extends the parent's address.
Vue 3 project fragment. Use the template or setup block in a component, import the named Vue APIs, and supply the reactive values referenced by the example.
const route = { path: '/rooms/:id', component: RoomLayout, children: [ { path: 'bookings', component: RoomBookings } ] }Build a layout with a shared heading and changing child content.
Define /campus/rooms as a child of a layout displaying Campus.
Expected result
At /campus/rooms, Campus stays visible and the nested outlet displays Rooms. - Programmatic Navigation: useRouter(), push, replace & History Stacks
Read the example and try it
Use push when the learner should be able to return with Back. A named route lets the router encode the parameter.
Vue 3 project fragment. Use the template or setup block in a component, import the named Vue APIs, and supply the reactive values referenced by the example.
const router = useRouter() function showRoom(id) { return router.push({ name: 'room', params: { id } }) }Compare Back behavior after push and replace.
Start at /home, push /rooms, then replace /rooms with /rooms/7.
Expected result
Back returns to /home. The replaced /rooms entry is absent from that history sequence. - Navigation Guards: Global beforeEach, Per-Route Guards & Auth Protection
Read the example and try it
A guard can redirect unauthenticated visitors to the login view. A server must independently verify access to protected records.
Vue 3 project fragment. Use the template or setup block in a component, import the named Vue APIs, and supply the reactive values referenced by the example.
router.beforeEach(to => { if (to.meta.requiresLogin && !session.signedIn) return { name: 'login' } })Test a denied route and a separately denied API request.
As an anonymous visitor, open /private and request its protected API directly.
Expected result
The client guard redirects or denies the route. The API independently returns 401 for missing credentials; it should not return private data.
State Management (Pinia) & Production
- State Management with Pinia: createPinia(), Store Architecture & Modern Vuex Comparison
Read the example and try it
Install a Pinia instance on the app before using a store in a component. A shared store lets separate views see the same booking count.
Vue app entry point with Pinia installed.
import { createPinia } from 'pinia' app.use(createPinia())Create Pinia, install it and access a store from a component.
Create Pinia, call app.use(pinia), then get a store whose initial count is zero and increment once.
Expected result
The mounted component displays 1. Components using that same installed store see the same count. - Pinia Store Deep Dive: State Mutations, Getters, Async Actions & $patch
Read the example and try it
An action owns the update while a getter derives the display value. Keep the capacity and bookings as the source fields.
Pinia store module. Import defineStore from pinia.
import { defineStore } from 'pinia' export const useRoom = defineStore('room', { state: () => ({ capacity: 4, booked: 0 }), getters: { left: s => s.capacity - s.booked }, actions: { reserve() { if (this.left > 0) this.booked++ } } })Separate a derived total from a save-and-update action.
Store seats=3, price=4. Save seats=5 in an action after a successful fake API response.
Expected result
The derived total changes from 12 to 20. A failed save must report failure and must not claim the new value was persisted. - TypeScript with Vue 3: Typing Props, Emits, Refs & Generic Components
Read the example and try it
Give the component's prop and emitted value explicit types. A parent passing the wrong type can then be caught by the type checker.
Child component in a Vue 3.4+ project. Save it in a .vue file and import it in the parent component.
<script setup lang="ts"> const props = defineProps<{ seat: number }>() const emit = defineEmits<{ reserve: [seat: number] }>() </script> <template><button @click="emit('reserve', props.seat)">Reserve</button></template>Check an unknown payload before using it as a typed prop.
Compare unknown inputs {seats:3} and {seats:"three"} before passing to a numeric prop.
Expected result
Accept the first, reject the second. A TypeScript assertion alone performs no runtime validation. - Unit & Component Testing with Vitest and @vue/test-utils
Read the example and try it
Test a component through its visible button. Check the emitted payload because that is what the parent receives.
Vitest component test with mount from @vue/test-utils and the SeatButton component.
const wrapper = mount(SeatButton, { props: { seat: 7 } }) await wrapper.get('button').trigger('click') expect(wrapper.emitted('reserve')).toEqual([[7]])Click a counter and assert the visible count after the update.
Start a component counter at 0. Trigger one click and wait for the update.
Expected result
The visible count is 1. Assert the rendered text after the interaction resolves. - Production Build, Tree-Shaking, Performance Audits & Intro to Nuxt 3 (SSR)
Read the example and try it
Preview the compiled Vite output locally before deployment. Inspect the network panel to check when lazy-loaded modules arrive.
Terminal inside your Vite project.
npm run build npm run previewInspect the build output and distinguish static assets from an SSR server.
Build a client-only Vite project and compare its output with an application that renders HTML on demand.
Expected result
The client build produces dist/index.html and referenced assets. An SSR deployment also requires its server entry, runtime and required dependencies; static assets alone cannot render on demand.
Build and check keyboard-accessible controls
A visible control also needs a name and a predictable keyboard action. A label linked by for and id gives the input an accessible name. A native button supports keyboard activation. CSS can improve appearance, but must preserve visible focus. Client validation helps users; the server must still validate submitted data.
Any modern browser; no framework dependency
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Study reminder</title>
<style>
:focus-visible { outline: 3px solid #075985; outline-offset: 3px; }
</style>
<form action="" method="get">
<label for="topic">Topic to revise</label>
<input id="topic" name="topic" required>
<button type="submit">Save reminder</button>
</form>
</html>Check the output
The page displays a labeled field and a button. Submitting a nonempty value adds topic to the URL; this example has no server-side storage.Add help text using aria-describedby. Test keyboard use at 200% zoom and confirm that the text remains readable.
Design a React component behavior test
Test what a student using the page can observe. For a counter, the important contract is its initial value and the result of activating its button. Avoid coupling the test to private state variable names or CSS classes. The pseudocode below describes a component-test plan; it is not executable JavaScript and does not require a particular test library.
Framework-independent test plan; adapt to your component test runner
Arrange: render the counter
Assert: visible count is 0
Act: activate the button named "Add one"
Assert: visible count is 1
Act: activate it again
Assert: visible count is 2Check the output
The behavior check passes only if each observed count matches the expected value. This is a test plan, not a runnable test file.Add a reset button. Write the behavior contract before choosing a framework-specific component testing tool.
Open the Vue learning path on DevStudyHub · Play coding games on this blog
No comments:
Post a Comment
Please do not enter any spam link in the comment box.