Vue.js interview cheat sheet
Vue 3 reactivity, Composition API, components, Pinia, Router and Nuxt
Vue interviews focus on Vue 3: how the Proxy-based reactivity works, ref vs reactive, computed vs watch, the <script setup> macros, and how components talk to each other. Senior rounds add the update queue (nextTick), compiler optimisations, performance, Pinia, Vue Router, Nuxt SSR and how Vue compares with Vue 2 and React. Read the 15-minute revision first, then use Quiz mode and answer out loud. Template snippets are illustrative; the plain-JS reactivity demos are runnable.
15-minute revision
- Vue is a progressive framework: declarative templates + a fine-grained reactivity system. An SFC (
.vue) holds<template>,<script>and<style scoped>in one file. - Options API groups code by option type (
data,methods,computed). Composition API groups code by feature insidesetup(). Both are built on the same reactivity core. <script setup>is compile-time sugar forsetup(): top-level bindings are usable in the template. Macros likedefineProps,defineEmits,defineModelanddefineExposeneed no import.ref()holds any value behind.valueand is auto-unwrapped at the top level of templates.reactive()returns a deep Proxy for objects only; replacing or destructuring it loses reactivity.- Vue 3 reactivity uses Proxy
getto track andsetto trigger. Deps are stored asWeakMap<target, Map<key, Dep>>. Vue 2 usedObject.defineProperty, so it could not detect new keys or array index writes. toRefs(state)turns each property into a linked ref so you can destructure safely.shallowRefonly tracks.valuereplacement; use it for big immutable data.computedis lazy and cached and should be pure.watchruns side effects on explicit sources (old and new values, lazy by default).watchEffectruns immediately and auto-tracks what it reads.v-ifadds or removes elements (cheap when false, costly to toggle).v-showonly togglesdisplay(cheap to toggle). In Vue 3v-ifhas higher priority thanv-foron the same element.- Always give
v-fora stable, unique:key(an id, not the index) so the diff can reuse and move the right DOM nodes and keep component state. v-modelon a component =modelValueprop +update:modelValueevent. Since 3.4defineModel()gives you a writable ref for it. Named models:v-model:title.- Data flow: props down, events up. Props are read-only. Use
provide/injectfor deep trees, slots (incl. scoped slots) to pass template content, and Pinia for shared app state. - DOM updates are batched in an async queue and flushed in a microtask. Use
await nextTick()to read the DOM after a state change. - Lifecycle (Composition):
onBeforeMount → onMounted → onBeforeUpdate → onUpdated → onBeforeUnmount → onUnmounted.setup()replacesbeforeCreate/created. Vue 3 renameddestroyedtounmounted. - Composables (
useX()) reuse stateful logic. They replace mixins, which had unclear sources and name clashes. - Compiler hints make Vue's virtual DOM fast: static hoisting, patch flags and block trees let the diff skip static content.
<Teleport>renders elsewhere in the DOM (modals).<KeepAlive>caches component instances.<Suspense>waits for async setup (still experimental). Pinia is the official store; Vuex is in maintenance mode.
Foundations & templates
What Vue is & Single-File Components
Vue is a progressive, component-based UI framework whose templates compile to render functions driven by reactive state.
- Progressive: you can drop Vue into one page via a script tag, or build a full SPA/SSR app with Vite, Vue Router, Pinia and Nuxt.
- Declarative rendering: the template describes the UI as a function of state. When reactive state changes, Vue re-renders only the affected components.
- A Single-File Component (
.vue) puts<template>,<script>/<script setup>and<style>in one file. Build tools (Vite +@vitejs/plugin-vue) compile it to a JS module. <style scoped>adds a unique data attribute (likedata-v-7ba5bd90) to elements and rewrites selectors, so styles do not leak to other components. Use:deep()to target child internals.- Apps start with
createApp(App).use(router).use(pinia).mount('#app'). In Vue 3 each app instance has its own config, unlike Vue 2's globalVue.use.
Interview questions
- What is Vue and why is it called progressive?
- What is a Single-File Component?
- How does
<style scoped>work?
Options API vs Composition API
Two ways to write the same component: by option type (Options) or by feature (Composition). Composition is the modern default for larger apps.
- Options API:
data,props,computed,methods,watchand lifecycle options on an object. Inside them you usethis. - Composition API: import
ref,computed,watch,onMountedand call them insidesetup()or<script setup>. Nothis. - Composition lets you group code by logical concern and move it into composables. That fixes the scattering problem of big Options components.
- Composition has better TypeScript inference (plain variables and functions) and minifies better (no
this.property names). - The Options API is fully supported and is itself implemented on top of the Composition API. You can mix them, e.g.
setup()inside an Options component.
Interview questions
- Options API vs Composition API: when would you choose each?
- What problem does the Composition API solve that mixins could not?
- Can you use both APIs in one component?
<script setup> & compiler macros
<script setup> is compile-time sugar for setup(); macros like defineProps and defineEmits are compiled away and need no import.
- Code in
<script setup>runs once per component instance. Top-level variables, functions and imports (including components) are available in the template. defineProps/defineEmitsdeclare props and events, with runtime objects or TypeScript types (defineProps<{ id: number }>()).- Since 3.5, destructured props are reactive:
const { size = 'md' } = defineProps(...). Wrap them in a getter to watch them:watch(() => size, ...). defineModel()(stable in 3.4) declares av-modelprop + update event.defineExpose({ focus })makes members visible to a parent template ref; by default the component is closed.defineOptions({ name, inheritAttrs: false })(3.3+) sets component options.defineSlotstypes slots.useSlots()/useAttrs()give slots and attrs at runtime.- It is compiled into a
setup()whose render function is inlined in the same scope, so templates access bindings directly without a proxy. This is faster than a normalsetup()return object.
Interview questions
- What does
<script setup>compile to? - Why don't you import
defineProps? - How do you call a child component's method from a parent with
<script setup>?
Template syntax & directives (v-bind, v-on, v-if, v-show, v-for)
Templates use {{ }} for text and v- directives for attributes, events, conditions and lists; each expression is a single JS expression.
{{ expr }}interpolates escaped text.v-htmlsets raw HTML and is an XSS risk with user content.v-bind:attr/:attrbinds attributes and props.:classand:styleaccept strings, objects and arrays. Since 3.4,:idalone means:id="id".v-bind="obj"spreads many attributes.v-on:event/@eventlistens to events. Modifiers:.prevent,.stop,.once,.self,.capture,.passive, and key modifiers like@keyup.enter.v-if/v-else-if/v-elsecreate and destroy elements and components.v-showkeeps the element and togglesdisplay: none.v-for="(item, i) in items" :key="item.id"renders lists. Keys let the diff match old and new nodes. Index keys break when items are inserted, removed or reordered.- In Vue 3,
v-ifhas higher priority thanv-foron the same element (the reverse of Vue 2). Filter with a computed or wrap in<template v-for>instead of combining them. - Dynamic arguments:
:[attrName]="value"and@[eventName]="handler". Custom directives (v-focus) are for low-level DOM access.
Interview questions
- Difference between
v-ifandv-show? - Why is
keyimportant inv-for? - Can you use
v-ifandv-foron the same element? - Why is
v-htmldangerous?
v-model & defineModel
v-model is two-way binding sugar: on inputs it is value + input, on components it is modelValue + update:modelValue.
- On native elements it picks the right pair:
value+inputfor text,checked+changefor checkboxes and radios,value+changefor selects. - Modifiers:
.lazy(sync onchange),.number(cast to number),.trim(trim whitespace). - On components (Vue 3):
v-model="x"expands to:modelValue="x" @update:modelValue="v => x = v". Vue 2 usedvalue+inputand the.syncmodifier. - Named and multiple models:
v-model:first="a" v-model:last="b". Each maps to afirstprop andupdate:firstevent. defineModel()(stable since 3.4) returns a ref that reads the prop and emits the update when you assign it. It accepts prop options like{ required: true, default: 0 }.- Custom modifiers:
const [model, modifiers] = defineModel({ set(v) { ... } })lets the child react tov-model.capitalize.
Interview questions
- How does
v-modelwork on a custom component in Vue 3? - How is Vue 3's
v-modeldifferent from Vue 2's? - Is
v-modelreal two-way binding?
Reactivity
ref vs reactive, unwrapping & toRefs
ref wraps any value in an object with .value; reactive makes an object deeply reactive via Proxy. Most teams default to ref.
ref(x)returns{ value }with a getter that tracks and a setter that triggers. Objects inside a ref are made deeply reactive withreactive().reactive(obj)returns a Proxy of the original. It only works on objects, arrays, Map and Set, not on primitives. The proxy is not equal to the original object.reactiveloses reactivity when you replace the whole object (state = reactive({...})) or destructure it into plain variables. A ref can always be reassigned via.value.- Unwrapping: top-level refs are auto-unwrapped in templates, and refs stored as properties of a
reactiveobject are unwrapped on access. Refs inside reactive arrays, Map or Set are not unwrapped. toRefs(state)converts each property into a ref that stays linked to the source, soconst { x, y } = toRefs(state)is safe.toRef(props, 'id')ortoRef(() => props.id)does it for one key.toValue(x)(3.3+) reads a ref, getter or plain value.isRef,unref,isReactive,readonly,toRawandmarkRaware the other common helpers.
Interview questions
- Difference between
refandreactive? - Why does destructuring a
reactiveobject break reactivity? - What is ref unwrapping?
- When would you use
toRef/toRefs?
computed vs watch vs watchEffect
computed derives a cached value; watch and watchEffect run side effects when reactive data changes.
computed(getter)is lazy and cached: it recomputes only when a dependency changed and someone reads it. Getters should be pure (no fetches, no mutations).- Writable computed:
computed({ get, set }). Since 3.4, a computed only triggers its dependents if its value actually changed. watch(source, cb, opts): source is a ref, a getter, a reactive object (implicitly deep) or an array of these. The callback gets(newVal, oldVal, onCleanup)and is lazy unlessimmediate: true.- Options:
deep(3.5 also accepts a depth number),immediate,once(3.4+), andflush: 'pre' | 'post' | 'sync'. Defaultpreruns before the component's DOM update;'post'(orwatchPostEffect) lets you read the updated DOM. watchEffect(fn)runs immediately and tracks whatever it reads synchronously. Reads after the firstawaitare not tracked.- Cancel stale async work with
onWatcherCleanup()(3.5+) or theonCleanupargument. Watchers created insetupstop on unmount; watchers created asynchronously must be stopped with the returned handle.
Interview questions
- Difference between
computedandwatch? - Difference between
watchandwatchEffect? - Why is a computed better than a method for derived data?
- How do you handle race conditions in a watcher that fetches data?
- When do watcher callbacks run relative to DOM updates?
Reactivity internals: Proxy, shallowRef & the update queue
Reading a reactive property inside an effect tracks it; writing it triggers the effects, which Vue's scheduler batches and flushes in a microtask.
reactive()wraps objects in a Proxy. Thegettrap callstrack(target, key);set/deletePropertycalltrigger(target, key). Nested objects are proxied lazily on access.- An effect (component render, computed, watcher) runs while being the active subscriber, so every tracked read records it as a dependency of that key.
- Proxy can intercept new properties, deletes, array index and
lengthwrites, and Map/Set methods, which Vue 2'sObject.definePropertycould not (it neededVue.set). shallowRefonly tracks.valuereplacement;shallowReactiveonly tracks root keys.triggerRef(r)forces an update after mutating a shallow ref.markRaw(obj)stops an object from ever being proxied (e.g. a map SDK instance).- Component updates are queued, deduplicated and flushed in a microtask (sorted parent before child). So 100 synchronous changes cause one re-render.
nextTick()returns a promise that resolves after the current flush. Useawait nextTick()before measuring or focusing DOM you just changed.
Interview questions
- How does Vue 3's reactivity system work?
- Why did Vue 3 switch from
Object.definePropertyto Proxy? - What is
nextTickand when do you need it? - When would you use
shallowReformarkRaw?
Components
Lifecycle hooks
A component is created, mounted, updated and unmounted; hooks let you run code at each stage.
- Setup / create:
setup()(Composition) runs first and replacesbeforeCreateandcreated. Reactive state exists but there is no DOM yet. - Mount:
onBeforeMountthenonMounted. InonMountedthe component's DOM exists, so you can use template refs, measure elements or start third-party libraries. - Update:
onBeforeUpdate/onUpdatedrun around a re-render caused by reactive changes. Do not change state inonUpdated; it can loop. - Unmount:
onBeforeUnmount/onUnmounted. Clean up timers, listeners, sockets and subscriptions here to avoid leaks. - Others:
onActivated/onDeactivated(<KeepAlive>),onErrorCaptured(child errors),onServerPrefetch(SSR). Debug:onRenderTracked/onRenderTriggered. - Hooks must be registered synchronously during
setup, not after anawaitor in asetTimeout, because Vue needs the current instance.
Interview questions
- Explain the Vue component lifecycle.
- Where should you fetch data:
created/setupormounted? - In what order do parent and child hooks run?
Props, emits & provide/inject
Props pass data down, emits send events up, and provide/inject passes data to any descendant without prop drilling.
- Props are declared with
defineProps(types,required,default,validator). They are one-way and read-only; Vue warns if a child mutates one. - To change a prop's value, emit an event and let the parent update it, or copy it into a local
refif it is only an initial value. - Emits are declared with
defineEmitsand fired withemit('save', payload). Parent listens with@save. Declaring them documents the API and keeps them out of$attrs. - Fallthrough attributes: attributes and listeners not declared as props/emits (like
class,id,@click) land on the child's root element. Turn off withinheritAttrs: falseand bind$attrsyourself. - provide / inject: an ancestor calls
provide(key, value), any descendant callsinject(key, default). Provide a ref to keep it reactive, and expose a function for changes. Use aSymbol/InjectionKeyfor keys. - Mutating object props (
props.user.name = 'x') is not blocked by Vue but breaks one-way data flow. Avoid it.
Interview questions
- What is one-way data flow and why does Vue enforce it for props?
- How do you pass data from child to parent?
- What is prop drilling and how does Vue solve it?
- Is injected data reactive?
- What are fallthrough attributes?
Slots: default, named & scoped
Slots let a parent pass template content into a child; scoped slots let the child pass data back to that content.
- Default slot:
<slot>Fallback</slot>in the child; anything between the parent's component tags goes there. - Named slots:
<slot name="header" />in the child,<template #header>(v-slot:header) in the parent. - Scoped slots: the child passes props to the slot (
<slot :item="item" />) and the parent receives them (<template #default="{ item }">). The content is compiled in the parent's scope. - Use scoped slots for renderless / headless components: the child owns logic and data, the parent owns markup (lists, tables, dropdowns).
- In Vue 3 all slots are functions (
this.$slots), called lazily by the child. Vue 2's$scopedSlotswas merged into$slots. - Check if a slot was provided with
useSlots()/$slots.footerto skip wrapper markup.
Interview questions
- What is a scoped slot?
- Slots vs props: when do you use which?
- What is a renderless component?
Composables (reusable logic)
A composable is a useX() function that uses the Composition API to encapsulate and reuse stateful logic.
- Naming:
useSomething. It can create refs, computeds and watchers and register lifecycle hooks; they bind to the calling component. - Return a plain object of refs (not a reactive object) so callers can destructure without losing reactivity.
- Accept refs, getters or plain values as input and normalise them with
toValue()inside awatchEffect/watch, so the composable reacts to changes. - Call composables synchronously at the top of
<script setup>/setup(). Each call creates new state; for shared state, create the state outside the function (module scope) or use Pinia. - Clean up side effects in
onUnmounted(or rely on watchers, which stop automatically). - VueUse is a large library of ready-made composables (
useMouse,useLocalStorage,useFetch,useDebounceFn).
Interview questions
- What is a composable?
- Composables vs mixins?
- How do you share state between components with a composable?
Teleport, KeepAlive, Suspense, Transition & async components
Built-in components solve rendering problems: render elsewhere, cache instances, wait for async deps and animate enter/leave.
<Teleport to="body">renders its content into another DOM node while keeping it a logical child (props, events, provide/inject still work). Used for modals, toasts and tooltips.defer(3.5+) lets the target be rendered later in the same tick;disabledrenders it in place.<KeepAlive>caches inactive component instances instead of unmounting them, so tabs keep state.include/exclude(by component name) andmax(LRU limit). Hooks:onActivated/onDeactivated.<Suspense>(still experimental) shows a#fallbackuntil async descendants are resolved: components with top-levelawaitin<script setup>or async components.<Transition>/<TransitionGroup>add enter/leave CSS classes (v-enter-from,v-enter-active,v-leave-to, ...) or JS hooks;TransitionGroupalso animates list moves.defineAsyncComponent(() => import('./Heavy.vue'))loads a component only when it renders (code splitting), with options for loading/error components, delay and timeout. Since 3.5 it also supports lazy hydration strategies such ashydrateOnVisible().
Interview questions
- What is
<Teleport>and when would you use it? - What does
<KeepAlive>do? - How do you lazy-load a component in Vue?
- What is
<Suspense>?
State, routing & Nuxt
State management: Pinia vs Vuex
Pinia is Vue's official store: simple defineStore with state, getters and actions, no mutations, great TypeScript and devtools.
- A store is created with
defineStore('id', ...)in options style (state,getters,actions) or setup style (a function returning refs, computeds and functions). - Actions can be sync or async and mutate state directly. There are no mutations and no
commit/dispatchstrings. - Destructuring a store loses reactivity for state/getters. Use
storeToRefs(store)for them; actions can be destructured directly. - Stores are modular by default (one file per store, no nested modules) and tree-shakable. Stores can use other stores.
- Extras:
$patch,$reset(options stores),$subscribe, plugins (e.g. persistence), Vue devtools time travel, and SSR support. - Vuex is in maintenance mode. Pinia is the recommended choice for new Vue 3 apps.
Interview questions
- Why choose Pinia over Vuex?
- When do you need a store at all?
- Why does destructuring a Pinia store break reactivity, and how do you fix it?
Vue Router: routes, guards & lazy loading
Vue Router maps URLs to components, supports nested and dynamic routes, guards for auth, and lazy-loaded route chunks.
- Create with
createRouter({ history: createWebHistory(), routes }).createWebHashHistoryuses#/pathand needs no server config; HTML5 history needs a server fallback toindex.html. - Dynamic segments:
/users/:id→route.params.id. UseuseRoute()(current route) anduseRouter()(navigation:push,replace,back). - Going from
/users/1to/users/2reuses the component, so lifecycle hooks do not run again. Watch() => route.params.idor useonBeforeRouteUpdate. - Guards: global (
beforeEach,beforeResolve,afterEach), per-route (beforeEnter), in-component (onBeforeRouteLeave,onBeforeRouteUpdate). Returnfalseto cancel, a route location to redirect, or nothing to continue. Thenext()argument is optional in Vue Router 4. - Lazy loading:
component: () => import('./views/Admin.vue')creates a separate chunk loaded on first visit. - Other features: nested routes with
<RouterView>, named views,metafields (requiresAuth),scrollBehavior, andprops: trueto pass params as props.
Interview questions
- What are navigation guards and what types exist?
- Hash mode vs history mode?
- Why does my component not refetch when the route param changes?
- How do you lazy-load routes and why?
Nuxt basics: SSR, file routing & data fetching
Nuxt is the Vue meta-framework: file-based routing, server-side rendering, auto-imports and a built-in server (Nitro).
- File-based routing: files in
pages/become routes (pages/users/[id].vue→/users/:id).layouts/,middleware/(route guards),plugins/andserver/api/follow conventions too. - Nuxt 4 (2025) puts app code in an
app/directory by default (app/pages,app/components), withserver/andshared/at the root. Existing Nuxt 3 layouts still work. - Universal rendering (default): the server renders HTML for the first request, then the client hydrates it and continues as an SPA. Benefits: faster first paint and SEO.
- Rendering modes per route via
routeRules: SSR, prerender (SSG), SWR / ISR caching, or client-only (ssr: false). - Fetch data with
useFetch/useAsyncData: they run on the server, serialise the result into the payload, and do not refetch on hydration.$fetchalone in setup would run twice (server and client). - Auto-imports for components, composables and Vue APIs.
server/api/*.tsfiles become API endpoints served by Nitro.
Interview questions
- What does Nuxt add on top of Vue?
- What is hydration?
- Why use
useFetchinstead of callingfetchinonMountedin Nuxt?
Internals, performance & comparisons
Virtual DOM & compiler-informed optimisations
Vue renders a virtual DOM, but its template compiler marks what can change so the runtime diff skips static parts.
- Templates compile to render functions that return VNodes. On update, the new VNode tree is patched against the old one and only the differences hit the real DOM.
- Vue only re-renders components whose tracked dependencies changed; a parent update does not re-render children whose props did not change. That's precise at the component level without
memo. - Static hoisting / caching: VNodes that never change are created once and reused on every render, and the diff skips them. Older versions hoisted them to module scope; 3.5 caches them per instance. Long static runs can be stringified to plain HTML.
- Patch flags: each dynamic node carries a bit flag (
TEXT,CLASS,STYLE,PROPS...) so the patch checks only those parts. - Block tree: a block collects its dynamic descendants into a flat array, so patching walks only dynamic nodes, not the whole tree. Structural directives (
v-if,v-for) start new blocks. - Keyed child diffing uses a longest increasing subsequence to move the fewest DOM nodes. Vapor Mode, an opt-in compile strategy without a virtual DOM, is in development.
Interview questions
- What is the virtual DOM and does Vue use it?
- What are patch flags and static hoisting?
- What is a block tree?
- How is Vue's re-render scope different from React's?
Performance optimisation
Load less code, render less, and keep reactivity cheap: lazy loading, stable props, shallow data, virtual lists and caching.
- Page load: lazy-load routes and heavy components, tree-shake imports, use SSR/SSG for content pages, and analyse bundles (e.g.
rollup-plugin-visualizer). - Props stability: pass primitive props that change only when needed. Passing
activeIdto every row re-renders all rows; passing:active="item.id === activeId"re-renders only two. v-oncerenders a subtree once;v-memo="[deps]"skips re-rendering a subtree (often a largev-forrow) unless the listed values change.- Large data:
shallowRef/shallowReactive/markRawavoid deep proxies; virtual scrolling (e.g.vue-virtual-scroller) renders only visible rows. - Computed caches derived data; since 3.4 computeds only trigger dependents when their value changes. Avoid creating new objects in computeds that feed other effects.
- Use
<KeepAlive>for expensive views users switch between, debounce input-driven watchers, and avoid unnecessary component abstractions in huge lists (each instance has a cost).
Interview questions
- How would you optimise a Vue page that renders a 10,000-row table?
- What does
v-memodo? - How do you reduce Vue bundle size and load time?
Vue 2 vs Vue 3
Vue 3 rewrote reactivity on Proxy, added the Composition API and better TypeScript, and changed several APIs; Vue 2 reached end of life on 31 Dec 2023.
- Reactivity:
Object.defineProperty(Vue 2) → Proxy (Vue 3). No moreVue.set/Vue.delete; new keys and array indexes are reactive. - App creation: global
new Vue()andVue.use→createApp()with per-app config, plugins and components. - New features: Composition API,
<script setup>, Fragments (multiple root nodes), Teleport, Suspense, multiplev-models,emitsoption,defineModel. - Removed: filters (use methods/computed),
$on/$off/$once(event bus; use mitt or a store),.sync,$listeners(merged into$attrs),$children. - Renamed:
destroyed→unmounted,beforeDestroy→beforeUnmount.v-ifnow beatsv-forin priority.v-modelusesmodelValue. - Smaller and faster: tree-shakable APIs, compiler optimisations, written in TypeScript. Vue 2.7 backported the Composition API to ease migration.
Interview questions
- What are the main differences between Vue 2 and Vue 3?
- Why couldn't Vue 2 detect
this.items[0] = xorthis.obj.newKey = 1? - How would you migrate a large Vue 2 app?
Vue vs React
Both are component-based and use a virtual DOM; Vue uses templates plus automatic fine-grained reactivity, React uses JSX plus explicit re-rendering with hooks.
- Templates vs JSX: Vue's HTML-based templates are compiled and optimised; React writes UI in JavaScript with JSX. Vue also supports JSX/render functions.
- Reactivity: Vue tracks dependencies automatically and mutation is fine (
count.value++). React relies on immutable updates viasetState, and re-renders the component and its children. - Hooks vs Composition API: React hooks re-run on every render and need dependency arrays and rules of hooks. Vue's
setupruns once; computed and watchers track deps automatically. - Batteries: Vue's core team maintains the router, Pinia, devtools and Vite. React leaves routing and state to the community (React Router, TanStack, Redux, Zustand), with Next.js as the main meta-framework.
- React has the larger ecosystem and job market and React Native for mobile. Vue is praised for a gentle learning curve and less boilerplate.
Interview questions
- Vue vs React: what are the key differences?
- How are Vue composables different from React hooks?
- When would you pick Vue over React for a project?