Vue Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. Why doesn't this watcher fire?
const state = reactive({ count: 0 }); watch(state.count, (n) => console.log(n));Correct answer:
state.countis a plain number here; watch a getter insteadwatchaccepts a ref, a reactive object, a getter function or an array of these. Passing a property value gives it a number, which can't be tracked.2. How does
watchEffectdiffer fromwatch?Correct answer:
watchEffectruns at once and tracks what it reads;watchis lazywatchEffectis concise when the effect uses the same state it depends on.watchgives precise control: only listed sources trigger it, and it can beimmediateoronce.3. How do you cancel a stale request when a watched
idchanges quickly (Vue 3.5+)?watch(id, async (newId) => { const controller = new AbortController(); onWatcherCleanup(() => controller.abort()); data.value = await fetch(`/api/items/${newId}`, { signal: controller.signal }).then((r) => r.json()); });Correct answer: Register cleanup with
onWatcherCleanupWithout cleanup, a slow old response can overwrite newer data. Before 3.5 the same was done with the
onCleanupargument of the callback.4. What does
{ deep: true }do on a watcher?Correct answer: Fires on nested mutations inside the watched object
Watching a
reactiveobject directly is deep by default; watching a getter is not. Deep watching large structures is expensive - in 3.5 you can pass a number to limit depth.5. When is
shallowRefa better choice thanref?Correct answer: For large data that only changes by replacing
.valuerefmakes nested objects deeply reactive via Proxies, which costs time for huge structures.shallowReftracks only.valuereplacement; usetriggerRefif you mutate and need to force an update.6. What does
toRefsdo?function useMouse() { const state = reactive({ x: 0, y: 0 }); return toRefs(state); } const { x, y } = useMouse();Correct answer: Turns each property into a ref linked to the original
toRef(state, 'x')does it for one property. Returning refs from composables is the convention precisely so consumers can destructure.7. What is a writable computed?
const fullName = computed({ get: () => `${first.value} ${last.value}`, set: (v) => { [first.value, last.value] = v.split(" "); }, });Correct answer: A computed with both a getter and a setter
By default computed refs are read-only. A setter is useful for
v-modelon derived values; the getter still must be pure.8. Why is mutating state inside a computed getter a bug?
Correct answer: Getters must be pure; side effects can cause loops
Vue may run the getter at any time (or not at all if nothing reads it). Use a watcher for side effects and keep computed purely derived.
9. How do you make a
watchcallback also run right away with the current value?watch(() => route.params.id, loadUser, { immediate: true });Correct answer: Pass
{ immediate: true }By default
watchis lazy and fires only on changes.immediateruns it once on creation;{ once: true }(3.4+) stops it after the first trigger.10. When does a watcher with
flush: 'post'run?Correct answer: After Vue has updated the DOM
By default watcher callbacks run before the component's DOM update.
flush: 'post'(orwatchPostEffect) is for reading layout;flush: 'sync'runs immediately on every change and should be rare.11. What do
defineModelmodifiers let you do?const [model, modifiers] = defineModel({ set(value) { return modifiers.capitalize ? value.charAt(0).toUpperCase() + value.slice(1) : value; }, }); // parent: <MyInput v-model.capitalize="text" />Correct answer: Read custom modifiers and transform the value
Destructuring
defineModelgives the ref and the modifiers object.get/setoptions transform values in both directions.12. How do you apply fallthrough attributes to an inner element instead of the root?
<script setup> defineOptions({ inheritAttrs: false }); </script> <template> <label class="field"><input v-bind="$attrs" /></label> </template>Correct answer: Disable
inheritAttrsand bind$attrsto the elementThis is common for wrapped inputs:
placeholder,aria-*and@inputshould reach the<input>, not the wrapper. Components with multiple roots must bind$attrsexplicitly.13. What is a scoped slot?
<!-- List.vue --> <li v-for="item in items" :key="item.id"><slot :item="item" /></li> <!-- usage --> <List :items="users" v-slot="{ item }">{{ item.name }}</List>Correct answer: A slot that passes data from the child to the parent's content
The child owns the iteration and layout; the parent decides how each item looks. It is Vue's equivalent of render props.
14. How do you keep provided state reactive but prevent descendants from mutating it?
const user = ref({ name: "Ann" }); provide("user", readonly(user)); provide("updateUser", (patch) => Object.assign(user.value, patch));Correct answer: Provide a
readonlyversion plus a function for changesKeeping mutations in the provider keeps the data flow traceable. Descendants that need to change state call the provided function.
15. Why use an
InjectionKeysymbol instead of a string forprovide/inject?export const ThemeKey: InjectionKey<Ref<string>> = Symbol("theme"); provide(ThemeKey, theme); const t = inject(ThemeKey); // Ref<string> | undefinedCorrect answer: Symbols avoid name collisions and carry the type
Put keys in a shared file.
injectreturnsT | undefinedunless you pass a default value.16. What does
defineAsyncComponentdo?const Chart = defineAsyncComponent(() => import("./Chart.vue"));Correct answer: Loads the component's code on demand, in a separate chunk
The options form adds
loadingComponent,errorComponent,delayandtimeout. Combine withv-ifso heavy widgets download only when needed.17. What does
defineExposedo in<script setup>?Correct answer: Opens selected properties to a parent with a template ref
<script setup>components are closed by default: a parent's ref gets nothing.defineExpose({ focus })lets the parent callchildRef.value.focus().18. What does the 3.5 reactive props destructure allow?
const { size = "md", count } = defineProps<{ size?: string; count: number }>(); const double = computed(() => count * 2);Correct answer: Destructured props stay reactive and take JS defaults
The compiler rewrites
counttoprops.count. To watch a destructured prop you still need a getter:watch(() => count, ...).19. How do you type component events with TypeScript?
const emit = defineEmits<{ change: [id: number]; update: [value: string]; }>();Correct answer: With a type-based
defineEmitsdeclarationCalling
emit('change', 'x')is then a type error, and parents get typed handler arguments.vue-tscchecks templates and SFCs in CI.20. What is a composable?
export function useMouse() { const x = ref(0), y = ref(0); const update = (e) => { x.value = e.pageX; y.value = e.pageY; }; onMounted(() => window.addEventListener("mousemove", update)); onUnmounted(() => window.removeEventListener("mousemove", update)); return { x, y }; }Correct answer: A function that reuses stateful Composition API logic
Each call creates its own state. By convention composables are named
useXxx, called synchronously insetup, and return refs. VueUse is a large collection of ready-made ones.21. What problems of mixins do composables solve?
Correct answer: Unclear property origin and name collisions
With composables, everything is explicitly imported and destructured, so you see where
xcame from and can rename on the fly. Mixins are not recommended in Vue 3.22. How should a composable accept arguments that might be refs, getters or plain values?
export function useFetch(url: MaybeRefOrGetter<string>) { watchEffect(() => load(toValue(url))); }Correct answer: Type them as
MaybeRefOrGetter, read withtoValue()Calling
toValueinsidewatchEffect(or awatchgetter) tracks the argument, souseFetch(() =>/api/${id.value})re-fetches whenidchanges.23. Why must composables be called synchronously in
<script setup>rather than in a callback?onMounted(() => { const { x } = useMouse(); // problem });Correct answer: Vue needs the active instance to register their hooks
Inside a callback there is no current instance, so
onUnmountedinside the composable isn't registered and listeners leak.<script setup>restores the instance after a top-levelawait, so calls after it still work.24. What happens when
<script setup>contains a top-levelawait?<script setup> const user = await fetch("/api/me").then((r) => r.json()); </script>Correct answer: The component becomes async and needs
<Suspense><Suspense>waits for async descendants and shows its#fallbackslot meanwhile. It is still marked experimental, so many teams prefer explicit loading state.25. How do you write a local custom directive in
<script setup>?<script setup> const vFocus = { mounted: (el) => el.focus() }; </script> <template><input v-focus /></template>Correct answer: A camelCase variable that starts with
v, likevFocusDirective hooks mirror lifecycle hooks (
created,mounted,updated,unmounted). Use directives for low-level DOM access; prefer components for anything with its own markup.26. What is a Vue plugin?
Correct answer: An object with
install(), registered withapp.use()Plugins can register global components and directives,
app.providevalues or addapp.config.globalProperties. Router and Pinia are installed as plugins.27. What does
<KeepAlive>do?<KeepAlive :max="5"> <component :is="currentTab" /> </KeepAlive>Correct answer: Caches inactive component instances so their state survives switching
Cached components receive
onActivated/onDeactivatedinstead of being unmounted.include,excludeandmaxcontrol what is cached.28. Why render a modal with
<Teleport to="body">?Correct answer: To place its DOM in
<body>, out of reach of parentoverflowTeleport changes only where the DOM goes; props, events and
provide/injectstill work as if the modal were in place.29. How does
<Transition name="fade">animate an element?Correct answer: It adds classes like
fade-enter-activeon enter and leaveIt works with
v-if,v-show, dynamic components and key changes.<TransitionGroup>handles lists, including move animations.30. What problem does
nextTicksolve here?showInput.value = true; await nextTick(); inputRef.value.focus();Correct answer: The input renders asynchronously, so it must exist first
State changes are batched; the DOM updates later in the same tick. Without
nextTick,inputRef.valueis stillnull.31. How do you lazy-load a route component?
Correct answer:
component: () => import('./views/Admin.vue')The bundler creates a separate chunk that is downloaded on first navigation. Don't use
defineAsyncComponentfor route components - the router handles it.32. How do you protect routes that require authentication?
router.beforeEach((to) => { if (to.meta.requiresAuth && !auth.isLoggedIn) { return { name: "login", query: { redirect: to.fullPath } }; } });Correct answer: A global
beforeEachguard that checksto.metaReturning
falsecancels navigation, returning a route redirects, returning nothing allows it. Real protection must still happen on the server API.33. Why doesn't the page update when navigating from
/users/1to/users/2?Correct answer: The same component instance is reused, so setup doesn't re-run
React to param changes with
watch(() => route.params.id, load, { immediate: true })oronBeforeRouteUpdate. Alternatively force a remount with<RouterView :key="route.fullPath" />.34. What does
props: truein a route definition do?{ path: "/users/:id", component: UserPage, props: true }Correct answer: Passes route params to the component as props
The component declares
defineProps<{ id: string }>()and becomes easier to reuse and test. A function form can map query params too.35. Why does reloading
/aboutreturn 404 in production withcreateWebHistory?Correct answer: The server has no such file and must fall back to
index.htmlClient-side routes exist only in JavaScript. Configure the host (nginx
try_files, Netlify/Vercel rewrites) to serve the SPA entry. Hash mode avoids this but produces/#/aboutURLs.36. What is the difference between
router.pushandrouter.replace?Correct answer:
pushadds a history entry,replaceswaps the current oneUse
replacefor redirects after login or when updating filters in the query string so the history isn't flooded. Both return a Promise that resolves after navigation.37. How are nested routes rendered?
{ path: "/settings", component: SettingsLayout, children: [ { path: "profile", component: Profile }, { path: "security", component: Security }, ], }Correct answer:
SettingsLayouthas its own<RouterView />Child paths without a leading
/are relative to the parent. A child with an empty path''renders at/settingsitself.38. Why does destructuring a Pinia store lose reactivity, and how is it fixed?
const store = useCartStore(); const { items, total } = storeToRefs(store); const { addItem } = store;Correct answer: The store is a reactive object;
storeToRefsfixes itPlain destructuring copies the current values.
storeToRefsskips actions and non-reactive properties, so actions are taken from the store itself.39. What is the difference between setup stores and option stores in Pinia?
Correct answer: Setup stores are a function; option stores are objects
Setup stores are more flexible (watchers, composables inside the store) but must return all state for devtools and SSR. Option stores provide
$reset()out of the box.40. What does
store.$patchoffer?cart.$patch((state) => { state.items.push(item); state.updatedAt = Date.now(); });Correct answer: Applies several changes as one grouped mutation
$patchtakes a partial object or a function. Direct assignments (cart.total = 0) also work;$patchis useful for batching and readability.41. Can Pinia actions be asynchronous?
Correct answer: Yes, actions can be
asyncandawaitAPI callsUnlike Vuex there are no separate mutations; actions change state directly.
$onActionlets you observe actions, including when they resolve or fail.42. How do you use a store outside of a component, e.g. in a router guard?
router.beforeEach((to) => { const auth = useAuthStore(); if (to.meta.requiresAuth && !auth.user) return "/login"; });Correct answer: Call
useStore()inside a function, after Pinia is installedAt module top level the Pinia instance may not be active yet (and in SSR it would be shared between requests). Calling the hook inside the guard uses the app's active Pinia.
43. Why isn't this Pinia getter cached?
getters: { byId: (state) => (id: number) => state.items.find((i) => i.id === id), }Correct answer: It returns a function, and each call runs the search again
Getters behave like computed properties. For frequent lookups by id, keep a computed map (
Mapor object keyed by id) and read from it.44. How can one Pinia store use another?
Correct answer: Call the other store's hook inside setup or actions
const user = useUserStore()inside a store works. Avoid two setup stores that read each other's state immediately during setup - that creates an initialization cycle.45. How do you style an element inside a child component from a scoped style?
.form :deep(.input) { border-color: red; }Correct answer: With the
:deep()pseudo-class:deep()removes the data attribute from the inner selector. Use it sparingly - it couples the parent to the child's internal markup.46. What does
v-bind()inside<style>do?<script setup>const color = ref("teal");</script> <style scoped>p { color: v-bind(color); }</style>Correct answer: Links a CSS value to reactive state
Vue sets a hashed CSS variable on the root element and updates it when
colorchanges, so the styles stay in CSS.47. How do you catch errors from descendant components?
Correct answer: With
onErrorCapturedin an ancestoronErrorCapturedcan show a fallback UI and returnfalseto stop propagation.app.config.errorHandleris the place to report errors to monitoring.48. Why
awaituser interactions in Vue Test Utils?const wrapper = mount(Counter); await wrapper.find("button").trigger("click"); expect(wrapper.text()).toContain("1");Correct answer:
triggerreturns a promise that waits for the DOM updateDOM updates are asynchronous. Awaiting
triggerorsetValue(ornextTick) makes assertions see the updated DOM.49. How do you test a component that uses Pinia stores?
Correct answer: Mount it with the
createTestingPinia()pluginActions become spies (
expect(store.addItem).toHaveBeenCalled()), andinitialStateseeds the store. Store logic itself is tested separately withsetActivePinia(createPinia()).50. Which tool type-checks
.vuefiles, including templates, in CI?Correct answer:
vue-tsc --noEmitPlain
tsccan't parse SFCs.vue-tsc(from the Vue language tools) checks script and template expressions; Vite itself only transpiles without type-checking.51. How do you animate items being added, removed and reordered in a list?
<TransitionGroup name="list" tag="ul"> <li v-for="item in items" :key="item.id">{{ item.text }}</li> </TransitionGroup>Correct answer:
<TransitionGroup>with keyed children<Transition>handles a single element;<TransitionGroup>handles each keyed item and uses FLIP for moves.52. Why prefer local imports over global
app.component()registration?Correct answer: Global components can't be tree-shaken and hide dependencies
With
<script setup>, importing a component is enough to use it. Global registration fits a few truly ubiquitous base components.53. How do you set component options like
inheritAttrs: falsein<script setup>?defineOptions({ inheritAttrs: false })Correct answer: With the
defineOptionsmacro (Vue 3.3+)Before 3.3 a separate normal
<script>block was needed.defineOptionscan also set a componentname.54. How do you watch several sources with one callback?
watch([page, () => filters.status], ([newPage, newStatus]) => { load(newPage, newStatus) })Correct answer: Pass an array of sources to
watchSources can be refs, reactive objects or getter functions. A property of a reactive object must be wrapped in a getter.
55. What does
{ once: true }do on a watcher (Vue 3.4+)?Correct answer: The callback runs on the first change, then stops
It replaces manually calling the stop handle inside the callback.
56. How do you stop a watcher before the component unmounts?
const stop = watch(source, callback) // later stop()Correct answer: Call the function that
watchreturnsWatchers created synchronously in
setupstop automatically on unmount. Watchers created asynchronously must be stopped manually to avoid leaks.57. How can you create a ref that debounces updates?
function useDebouncedRef(value, delay = 300) { let timer return customRef((track, trigger) => ({ get() { track(); return value }, set(v) { clearTimeout(timer); timer = setTimeout(() => { value = v; trigger() }, delay) }, })) }Correct answer: With
customRef, controlling track and triggercustomRefgives explicit control over tracking. It can be used withv-modellike a normal ref.58. You mutate an array inside a
shallowRef. Why doesn't the view update, and how do you fix it?const rows = shallowRef([]) rows.value.push(newRow)Correct answer: Only replacing
.valueis tracked; usetriggerRef(rows)shallowRefskips deep reactivity for performance; you decide when the change is announced.59. What does
<Suspense>do with a component that has a top-levelawaitin<script setup>?Correct answer: Shows
#fallbackuntil async dependencies resolveWithout a
<Suspense>ancestor such a component won't render.<Suspense>is still marked experimental.60. How do you warn the user before leaving a route with unsaved changes?
onBeforeRouteLeave(() => { if (dirty.value) return confirm('Leave without saving?') })Correct answer:
onBeforeRouteLeave, returningfalseIn-component guards know the component's state. Closing the tab needs a separate
beforeunloadlistener.61. What are the two common ways to load data for a route?
Correct answer: After navigation with a loader, or before it in a guard
Fetching after gives instant feedback; fetching before avoids showing an incomplete page. The choice is a UX trade-off.
62. How do you keep filters in the URL query and react to their changes?
const route = useRoute() watch(() => route.query.status, (status) => load(status)) router.push({ query: { ...route.query, status: 'open' } })Correct answer: Read
route.queryand watch it with a getterURL state survives reloads and can be shared. Query values are strings (or arrays) and need parsing.
63. What are named views in Vue Router?
<RouterView name="sidebar" /> <RouterView />Correct answer: Several
<RouterView>outlets on one levelThey suit layouts like a main area plus a sidebar that differ per route.
64. How does a route
aliasdiffer from aredirect?Correct answer: An alias keeps the typed URL, a redirect changes it
Aliases are useful for alternative URLs. For SEO, pick one canonical URL.
65. How do you know whether
router.push()actually navigated?const failure = await router.push('/admin') if (isNavigationFailure(failure, NavigationFailureType.aborted)) { /* blocked by a guard */ }Correct answer: Await it and use
isNavigationFailureNavigation can be aborted by a guard, cancelled by a newer navigation or be duplicated; these aren't exceptions.
66. Does a setup store have
$reset()like an option store?Correct answer: Not by default: you write your own
$resetPinia can't know the initial state of arbitrary
refs in a setup function, so it can't generate$reset.67. How do you log every action of a Pinia store and its errors?
store.$onAction(({ name, after, onError }) => { after(() => log(name, 'ok')) onError((e) => log(name, e)) })Correct answer: Subscribe with
$onAction$onActionis also the basis for analytics or undo plugins. It returns a function to unsubscribe.68. What does VueUse provide?
Correct answer: A collection of ready-made composables
Composables handle cleanup and SSR edge cases, so you don't rewrite common browser-API wrappers.
69. What do CSS Modules in an SFC look like?
<template><p :class="$style.error">Oops</p></template> <style module>.error { color: red; }</style>Correct answer:
<style module>, exposed through$styleUnlike
scoped, which adds data attributes, CSS Modules rename classes, making them safe to pass to child components.70. How do you style slot content passed in by the parent from a component's scoped styles?
:slotted(p) { margin: 0; }Correct answer: Use the
:slotted()pseudo-selectorSlot content belongs to the parent's scope, so normal scoped selectors don't match it.
:global()escapes scoping entirely.71. When is
shallowMountuseful in Vue Test Utils?Correct answer: To stub child components and test one in isolation
It isolates the unit, but heavy stubbing can hide integration bugs; many teams prefer
mountwith selected stubs.72. In a component test, why
await flushPromises()after clicking a button that triggers an API call?Correct answer: To let pending promises resolve before the assertions
await trigger()waits only for Vue's DOM update; network promises need an extra flush.73. What should happen to focus after client-side navigation in an SPA for accessibility?
Correct answer: Move it to the new page's main heading or content
Without a full page load, keyboard and screen reader users can be stuck on the old link. A skip link also helps.
74. How do you run a Vite build with settings from
.env.staging?Correct answer:
vite build --mode stagingThe mode selects which
.env.[mode]file is loaded.import.meta.env.MODEcontains the current mode.75. Why should production builds use Vue's production mode?
Correct answer: It removes dev warnings, making the bundle smaller
Vite does this automatically for
vite build. Shipping development builds leaks warnings and costs performance.