Vue Senior 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. How does Vue 3 track reactive dependencies?
Correct answer: Proxy
gettraps record subscribers,settraps notify themEffects (render functions, computed, watchers) register themselves while they run. Proxies also catch property addition/deletion and array index changes, which Vue 2's getters/setters could not.
2. Why is
reactive(obj) === objfalse, and why does it matter?Correct answer: It returns a Proxy, and writing to the original skips tracking
Always work with the proxy. Calling
reactiveon the same object returns the same proxy, andtoRaw(proxy)gives back the original when you need untracked access.3. When should you use
markRawon a value stored in reactive state?const map = shallowRef(markRaw(new mapboxgl.Map({ container: "map" })));Correct answer: For third-party instances like maps and editors
Proxying complex class instances costs performance and can break libraries that compare identities or use private fields.
markRawtells Vue never to convert the object.4. Why does changing state 100 times in one handler cause only one re-render?
Correct answer: Updates are queued and flushed once in a microtask
Each mutation triggers effects, but render jobs are deduplicated in a queue.
nextTick()returns the promise of that flush.5. What is
effectScopefor?const scope = effectScope(); scope.run(() => { const doubled = computed(() => counter.value * 2); watch(doubled, log); }); scope.stop();Correct answer: Collecting effects so they can be disposed together
Components create a scope automatically. Manual scopes are used in libraries and shared composables (e.g. a singleton store created outside components) to avoid leaking effects.
6. Since Vue 3.4, what happens when a computed recalculates to the same value?
Correct answer: Dependents are not triggered at all
const isEven = computed(() => count.value % 2 === 0)no longer re-runs downstream effects whencountgoes from 2 to 4. Returning a new object each time still defeats this.7. What goes wrong when a lifecycle hook is registered after
awaitin a plainsetup()function?export default { async setup() { const data = await load(); onMounted(() => init(data)); // problem }, };Correct answer: The current instance is lost, so the hook isn't registered
Hooks,
watchandinjectrely on the active instance, which is only set during synchronous setup. Register them before the firstawait, or use<script setup>, whose compiler preserves the context.8. How do you share one instance of a composable's state across all components that use it?
export const useOnlineStatus = createSharedComposable(() => { const online = ref(navigator.onLine); useEventListener(window, "online", () => (online.value = true)); return { online }; });Correct answer: Wrap it in a helper that runs it once in an
effectScopeEach normal call creates new state and listeners. VueUse's
createSharedComposablecounts subscribers and stops the scope when the last component unmounts.9. What makes Vue's virtual DOM "compiler-informed"?
Correct answer: Patch flags and hoisting let it diff only dynamic parts
Patch flags tell the runtime that, for example, only
classor text can change. Block trees flatten dynamic nodes so the diff skips static structure entirely.10. Why are templates generally preferred over hand-written render functions in Vue?
Correct answer: The compiler can optimize templates, but not render functions
Render functions and JSX are useful for highly dynamic output (e.g. a library rendering arbitrary trees), but you lose compile-time optimizations.
11. What goes wrong when
v-foruses the index askeyand items are inserted at the top?Correct answer: Vue reuses nodes by position, so local state shifts
With stable ids Vue moves existing nodes. Index keys only work for static lists or lists without component state.
12. How can changing the
keyof a component be used intentionally?<UserForm :key="user.id" :user="user" />Correct answer: To force a full remount with fresh state
A new key means a new component instance. It is a simple way to reset forms when switching entities, at the cost of recreating the subtree.
13. What does
v-memodo?<div v-for="item in list" :key="item.id" v-memo="[item.id === selectedId]">...</div>Correct answer: Skips updating the subtree unless a listed value changes
Useful for very large lists where selection changes affect only two items.
v-oncerenders once and never updates;v-memois the conditional version.14. Why can passing
activeIdto every list item make large lists slow?<ListItem v-for="item in list" :key="item.id" :id="item.id" :active-id="activeId" />Correct answer: Every item re-renders when
activeIdchangesChild components update when any prop changes. Keeping props stable means only the two items whose
activeflag flips will re-render.15. How do you render a list of 10,000 rows efficiently?
Correct answer: Virtualize it and render only the visible rows
Rendering every row creates many DOM nodes and component instances. Virtualization keeps the DOM small regardless of list length.
16. Why might wrapping large API data in
reactive/refbe costly, and what is the alternative?Correct answer: Deep reactivity proxies nested objects; use
shallowRefDeep proxies add overhead on access and tracking. For large read-mostly data, shallow reactivity plus replacing the whole value keeps updates cheap.
17. How do you reduce the initial bundle of a large Vue SPA?
Correct answer: Lazy-load routes and heavy components with
import()Route-level code splitting is the biggest win. Vue's APIs are tree-shakable, so unused features like
<Transition>are not bundled unless imported.18. What does the runtime-only build of Vue lack, and why is it the default with Vite?
Correct answer: The template compiler, since SFCs are precompiled at build
You only need the full build when compiling templates in the browser at runtime (e.g. from strings in HTML). That is also a security risk with user content.
19. Why does
<KeepAlive>withoutmaxrisk memory growth?Correct answer: Every visited instance stays cached with its DOM
maxturns the cache into an LRU. Useincludeto cache only views where preserving state actually helps (e.g. a filtered list the user returns to).20. What is cross-request state pollution in Vue SSR?
// store.js export const state = reactive({ user: null });Correct answer: A module singleton on the server leaks data between users
On the server, create app, router and stores per request (
createApp()factory,app.provide, Pinia per request). Pinia and Nuxt handle this when used correctly.21. What commonly causes hydration mismatches in Vue SSR?
Correct answer: Values that differ on server and client, or invalid HTML nesting
Move browser-only rendering to
onMountedor<ClientOnly>(Nuxt). Vue 3.5 addsdata-allow-mismatchto silence expected differences such as timestamps.22. What does lazy hydration in Vue 3.5 enable?
const Comments = defineAsyncComponent({ loader: () => import("./Comments.vue"), hydrate: hydrateOnVisible(), });Correct answer: Async components hydrate only when a condition is met
Other strategies include
hydrateOnIdle,hydrateOnInteractionandhydrateOnMediaQuery. The HTML is visible immediately, but JS for below-the-fold parts loads later.23. Why use
useId()(3.5+) forid/aria-*attributes?Correct answer: Its IDs match on the server and on the client
A random or incrementing module counter produces different values on server and client.
useIdties the ID to the component's position in the tree.24. Which lifecycle hooks run during SSR?
Correct answer: Only setup code and
onServerPrefetchAvoid side effects in setup that need cleanup (timers, subscriptions) -
onUnmountednever runs on the server, so they leak. Put them inonMounted.25. Why do many teams use Nuxt instead of hand-rolled Vue SSR?
Correct answer: It handles per-request setup, data transfer and routing
useFetch/useAsyncDatafetch on the server and transfer the result in the payload, so the client doesn't refetch during hydration.26. How is Pinia state transferred from the server to the client?
Correct answer: It is serialized into the page and set before mounting
Serialization must be safe against XSS (e.g.
devalue). Nuxt's Pinia module does this automatically. Non-serializable values (class instances, functions) don't survive.27. Why is mounting Vue on server-rendered HTML that contains user content dangerous?
Correct answer: The full build compiles in-DOM HTML, so
{{ }}can executeNever let user content become part of a template. Escape it on the server or use precompiled SFCs, where user data is only ever bound as data.
28. Is binding a user-provided URL to
:hrefsafe in Vue?Correct answer: No: Vue doesn't sanitize
javascript:URLsEscaping prevents breaking out of the attribute, not malicious schemes. Validate that the URL starts with
https://or is relative before storing it.29. Why is binding user-controlled values to
:stylerisky?Correct answer: Malicious CSS can overlay fake UI or leak data via
url()Prefer binding only specific properties (e.g.
color) from user input, validated against an allow-list, and never a whole user-provided style object.30. When is a module-level composable singleton enough instead of Pinia?
const state = reactive({ items: [] }); export function useCart() { return { items: readonly(state.items), add } }Correct answer: In a client-only app with simple shared state
Pinia adds devtools time travel, plugins, HMR, a testing helper and per-request instances for SSR. For SSR, module singletons are a state-pollution bug.
31. What is a good way to organize a large Vue codebase?
Correct answer: By feature: each one owns its components and store
Feature folders keep related code together and make boundaries visible; lazy-loaded routes map naturally onto features. Enforce imports between features with lint rules.
32. Which Vue 2 patterns must be replaced when migrating to Vue 3?
Correct answer: Global
Vue.*APIs, the$onevent bus and filtersOther changes: component
v-modelusesmodelValue/update:modelValue,$listenersmerged into$attrs, and multiple root nodes are allowed. Vue 2 reached end of life at the end of 2023.33. How do you migrate a large Options API codebase to the Composition API?
Correct answer: Incrementally, since both APIs can work side by side
A component can even use
setup()alongside options. Start with logic currently in mixins, which benefits most from composables.34. How do you expose a Vue component as a native Custom Element?
const MyWidget = defineCustomElement(Widget); customElements.define("my-widget", MyWidget);Correct answer: With
defineCustomElementStyles are injected into the shadow root. Props map to attributes/properties and emitted events become
CustomEvents. Useful for embeddable widgets.35. What does a global
app.config.errorHandlergive you thatonErrorCaptureddoesn't?Correct answer: One place to report all uncaught errors to monitoring
Use
onErrorCapturedfor local error boundaries with fallback UI, and the global handler (or Sentry's Vue integration) for reporting.36. How do you write a generic component (e.g. a typed select)?
<script setup lang="ts" generic="T extends { id: string }"> defineProps<{ items: T[]; modelValue: T | null }>(); defineEmits<{ "update:modelValue": [value: T] }>(); </script>Correct answer: With the
genericattribute on<script setup>The type parameter is inferred from props at the usage site, so slot props and events are typed for the specific item type.
37. What does
defineSlotsadd?defineSlots<{ default(props: { item: User }): any; empty(): any; }>();Correct answer: Type checking for slot names and scoped slot props
Without it, slot props are
anyin the parent. It is type-only and compiled away.38. How do you type a template ref to a child component?
const modal = useTemplateRef<InstanceType<typeof Modal>>("modal"); modal.value?.open();Correct answer:
InstanceType<typeof Component>The value is
nullbefore mount, hence optional chaining. Prefer props/events over calling child methods; exposing methods is for imperative APIs likefocus()oropen().39. How do you implement role-based access with route meta?
{ path: "/admin", component: Admin, meta: { roles: ["admin"] } } router.beforeEach((to) => { const roles = to.matched.flatMap((r) => r.meta.roles ?? []); if (roles.length && !roles.some(auth.hasRole)) return { name: "forbidden" }; });Correct answer: Check
to.matchedso meta from parent routes applies to their children tooto.metais a shallow merge of parent and child meta, so child values overwrite parent ones;to.matchedgives each level separately. Type meta viaRouteMetamodule augmentation.40. How do you restore scroll position when the user navigates back?
createRouter({ history: createWebHistory(), routes, scrollBehavior: (to, from, saved) => saved ?? { top: 0 }, });Correct answer: With the
scrollBehavioroption of the routersavedis provided only for popstate navigations. You can also scroll toto.hashor return a Promise to wait for async content.41. When would you call
router.addRoute()?Correct answer: To register routes at runtime, like tenant modules
If you add a route matching the current location, navigate again (
router.replace(router.currentRoute.value.fullPath)) so it takes effect.removeRoutedeletes it.42. How do guards handle async work like fetching permissions?
Correct answer: Guards can be
async, and navigation waits for themKeep guards fast or cache results - every navigation waits. The older
next()callback style is still supported but returning values is recommended.43. What can a Pinia plugin do?
pinia.use(({ store }) => { store.$subscribe((mutation, state) => localStorage.setItem(store.$id, JSON.stringify(state))); });Correct answer: Add properties to every store and react to changes
Plugins run for every store when it is first used. Popular plugins add persistence; typing new properties is done with
PiniaCustomPropertiesaugmentation.44. What is the difference between
$subscribeand awatchon store state?Correct answer:
$subscribefires once per$patch, with mutation infoSubscriptions added inside a component are removed when it unmounts unless
detachedis set.$onActionis the equivalent for actions.45. Why must setup stores return every piece of state?
Correct answer: Pinia only knows about the refs that are returned
If you need privacy, return it and treat it as internal by convention, or use a separate private store. Returned refs become
state, computed become getters.46. How do you test a composable that uses lifecycle hooks or
inject?Correct answer: Call it inside a small host component in the test
Composables that only use reactivity can be called directly. Those needing an instance require a component context;
providevalues can be passed viaglobal.providein Vue Test Utils.47. How do you test a component that uses Vue Router?
Correct answer: Install a real router with
createMemoryHistoryMemory history works in Node. Alternatively stub
RouterLinkand mockuseRoutefor isolated tests; real routers catch more integration bugs.48. What is the main trade-off between component tests and end-to-end tests?
Correct answer: Component tests are fast; E2E is realistic but flakier
Most logic is covered by unit/component tests (Vitest + Vue Test Utils), with a smaller set of E2E tests (Playwright, Cypress) for critical user flows.
49. When would you write a render function with
h()?const Heading = (props, { slots }) => h(`h${props.level}`, slots.default?.());Correct answer: When the structure is highly dynamic, like a runtime tag
Functional components like this have no state or instance. For most UI, templates are clearer and better optimized.
50. What does
createRendererfrom@vue/runtime-coreallow?Correct answer: Building a renderer that targets something besides the DOM
You implement node operations (create, insert, patch props), and the reactivity and component system work on top of them. Libraries like TresJS use this for WebGL.
51. What does the
previousargument of a computed getter (Vue 3.4+) allow?const max = computed((previous) => { const next = Math.max(...values.value) return previous !== undefined && previous > next ? previous : next })Correct answer: Reading the previously computed value
Returning the old object when nothing meaningful changed keeps references stable for downstream computeds and watchers.
52. What does
deep: 2on a watcher do (Vue 3.5+)?Correct answer: Tracks nested changes up to two levels deep
Deep watching of huge objects traverses everything on each change. Limiting depth reduces that cost.
53. How do you type a global property like
$tadded withapp.config.globalProperties?declare module 'vue' { interface ComponentCustomProperties { $t: (key: string) => string } }Correct answer: Augment
ComponentCustomPropertiesinvueGlobal properties are mainly for templates and the Options API; in
<script setup>preferprovide/injector a composable.54. How do you stream SSR HTML to the client instead of waiting for the whole page?
Correct answer: Use
renderToWebStreamorrenderToNodeStreamThe browser can start parsing earlier, improving time to first byte. Headers and status must be decided before streaming starts.
55. What does
data-allow-mismatch(Vue 3.5+) do?<span data-allow-mismatch="text">{{ new Date().toLocaleString() }}</span>Correct answer: Silences hydration warnings for an expected difference
Use it for unavoidable differences like dates. It hides the warning but doesn't fix it, so keep its use narrow.
56. What is
onServerPrefetchfor?Correct answer: Awaiting data so the server renders with it
The server waits for the returned promise before rendering. The data must then be serialized to avoid refetching on the client.
57. Why does Nuxt warn against calling
$fetchdirectly in<script setup>for page data?Correct answer: It runs on the server and then again in the browser
Double fetching wastes requests and can cause hydration mismatches.
$fetchis fine in event handlers.58. Why use Nuxt's
useStateinstead of a module-levelreffor shared state?Correct answer: It is per-request; a module ref is shared by all users
Module-level state is a classic cross-request leak in SSR. Pinia with Nuxt is also request-scoped.
59. When is
router.beforeResolvethe right place for a check?Correct answer: Right before confirming navigation, after all guards
It's a good spot for permission checks or fetching that need all route components loaded.
afterEachcan't cancel navigation.60. What is the modern way to redirect or cancel inside a Vue Router 4 guard?
router.beforeEach((to) => { if (to.meta.requiresAuth && !auth.loggedIn) return { name: 'login', query: { redirect: to.fullPath } } })Correct answer: Return
falseor a route locationReturning values avoids bugs like calling
next()twice or never. Guards can also be async functions.61. How do you combine route transitions and
<KeepAlive>with<RouterView>?<RouterView v-slot="{ Component }"> <Transition name="fade" mode="out-in"> <KeepAlive><component :is="Component" /></KeepAlive> </Transition> </RouterView>Correct answer: Use the
v-slotof<RouterView>Vue Router 4 removed the old wrapper pattern; the slot gives full control over the order of wrappers.
62. What is
skipHydratein Pinia for?Correct answer: Keeping state that the server payload shouldn't overwrite
Client-only values like a persisted cart would otherwise be replaced by the empty server state.
63. Why add
acceptHMRUpdateto Pinia store files?Correct answer: So editing a store hot-replaces it without a page reload
Without it, Vite falls back to a full reload when the store module changes.
64. What does
<Teleport defer>(Vue 3.5+) solve?Correct answer: Teleporting into a target that renders later in the same cycle
Without
defer, the target must already exist in the DOM when the teleport mounts.65. What does returning
falsefromonErrorCaptureddo?Correct answer: Stops the error from propagating any further
It lets a boundary component fully handle an error (e.g. show a fallback) without duplicate global reports.
66. How do you mock API calls in component tests without mocking
fetchper test?Correct answer: Intercept them with Mock Service Worker handlers
The same handlers can be reused in tests, Storybook and local development, and tests stay independent of the HTTP library.
67. How do you build a Vue component library with Vite without bundling Vue itself?
Correct answer: Use library mode with
vueas externalBundling Vue would create two Vue instances in the consumer app, breaking reactivity and
provide/inject.68. How do you type a complex prop in the Options API?
props: { user: { type: Object as PropType<User>, required: true }, }Correct answer: Cast the constructor with
PropType<T>Runtime
typechecks only the constructor (Object);PropTypegives TypeScript the exact shape.69. Why is a global
app.provide()often better thanglobalPropertiesfor app-wide services?Correct answer: Injected values are explicit, typed and easy to override
globalPropertiesare implicitthisadditions mostly suited to the Options API.70. How are
<Teleport>contents handled in SSR?Correct answer: They're collected in the context's
teleportsFrameworks like Nuxt do this automatically; hand-rolled SSR must handle it, or hydration of modals fails.
71. Why can a
reactivearray of 50,000 objects make filtering slow, and what helps?Correct answer: Each access is tracked;
shallowRefavoids deep trackingRead-only data rarely needs deep reactivity.
markRawobjects orshallowRefcut overhead dramatically.72. How do you keep the initial value of a prop as local editable state without warnings?
const props = defineProps<{ initialTitle: string }>() const title = ref(props.initialTitle)Correct answer: Copy it into a local
refLater prop changes won't update the copy; if they should, watch the prop or use
defineModelinstead.73. How do micro-frontends share one Vue runtime with Module Federation?
Correct answer: Declare
vueas a shared singletonMultiple Vue copies break
provide/inject, devtools and memory. Version ranges must be compatible.74. When does a component with an
async setup()need special care in tests?Correct answer: It must be wrapped in
<Suspense>before assertionsTest helpers often mount a wrapper with
<Suspense>and then wait for promises to resolve.75. What is a safe migration strategy from Vuex to Pinia in a large app?
Correct answer: Migrate module by module while both libraries coexist
Pinia has no mutations or nested modules, so each Vuex module becomes a separate store with actions.