Vue Interview Preparation
# CHAPTER 27
Vue Interview Preparation
1. Chapter Introduction
This chapter compiles the 50 most-asked Vue.js interview questions from top tech companies. Master these to ace frontend developer interviews confidently.---
Section A: Fundamentals (Q1–15)
Q1. What is Vue.js? What makes it different from React and Angular? Vue is a progressive JavaScript framework for building UIs. Unlike React (library, JSX), Vue uses HTML templates. Unlike Angular (full framework, TS-only), Vue is approachable and progressive — adoptable from a CDN script tag to a full SPA.
Q2. What is the Vue 3 reactivity system? Vue 3 uses JavaScript Proxy to intercept property reads (dependency tracking) and writes (triggering updates). When reactive data changes, Vue re-renders only the specific DOM nodes that depend on it.
Q3. What is the difference between ref() and reactive()?
ref() wraps any value (including primitives) in a reactive container — access via .value in scripts, auto-unwrapped in templates. reactive() wraps objects — properties are directly reactive without .value. Recommendation: use ref() for everything for consistency.
Q4. Why does destructuring a reactive() object break reactivity?
reactive() wraps an object in a Proxy. Destructuring const { name } = reactive({ name: 'Alice' }) extracts the primitive string — it's no longer connected to the Proxy. Solution: use toRefs() or use ref() instead.
Q5. What is the Composition API?
Vue 3's way of organizing component logic by feature instead of option type. Uses setup() or <script setup> with composable functions — enables logic reuse through composables, unlike the Options API's mixins.
Q6. What are Vue composables?
Functions prefixed with use that encapsulate and reuse stateful logic with Vue's reactivity. Example: useFetch, useLocalStorage, useCounter. Unlike mixins, composables have explicit return values, no namespace conflicts.
Q7. What is <script setup>?
Syntactic sugar for the Composition API. Variables, functions, and imports declared in <script setup> are automatically available in the template — no explicit return {} needed. Compiler macros like defineProps, defineEmits are available.
Q8. Explain Vue's component communication patterns.
-
1.
Parent→Child:
defineProps(data flows down)
-
2.
Child→Parent:
defineEmits(events bubble up)
- 3. Sibling/distant: Pinia store (global state)
-
4.
Parent→deep child:
provide/inject
-
5.
Custom
v-modelon components
Q9. What is v-model and how does it work?
v-model is syntactic sugar for :modelValue="value" @update:modelValue="value = $event". On native inputs: binds to :value + @input. On custom components: the component must accept modelValue prop and emit update:modelValue.
Q10. What is the difference between computed and watch?
computed: Returns a derived value, cached until reactive deps change. Use for calculations.
watch: Runs side effects when data changes. Use for API calls, localStorage, timers.
Never use async in computed — use watch instead.
Q11. What are lifecycle hooks? Name the most important ones. Hooks into component lifecycle phases:
-
onMounted: DOM ready — fetch data, init 3rd-party libs
-
onUpdated: After DOM patches — read updated DOM
-
onUnmounted: Cleanup — remove listeners, clear timers
-
onBeforeUnmount: Component still accessible before removal
Q12. What is Vue Router and how does it work?
Vue Router is the official client-side router. <RouterView> renders the current route's component. <RouterLink> creates SPA-navigation links. Navigation guards (beforeEach) run middleware before route transitions.
Q13. What is Pinia and how does it differ from Vuex? Pinia is Vue 3's official state manager. Unlike Vuex, it has: no mutations (direct state changes), simpler API matching Composition API patterns, better TypeScript support, modular by default (each store is separate file), and devtools support.
Q14. What is provide/inject in Vue?
Dependency injection across component hierarchy. A parent provides data:
Any descendant injects it:
Used for theme, auth context, and plugin-level data without prop drilling.
Q15. What is the difference between v-if and v-show?
v-if removes/adds element to DOM (true DOM operation). v-show toggles display: none (element stays in DOM). Use v-show for frequent toggles (modal, dropdown). Use v-if for rarely shown elements or role-based content.
---
Section B: Components & Patterns (Q16–30)
Q16. What is a Single File Component (SFC)?
A .vue file with three sections: <script>, <template>, <style scoped>. Encapsulates component logic, markup, and styles together. Processed by Vite + Vue compiler.
Q17. What does <style scoped> do?
Adds a unique data attribute to all elements in the component and its CSS selectors, making CSS private to that component. Prevents style conflicts between components.
Q18. What is the slot system?
Slots allow parent components to inject content into child component templates. Default slot: <slot />. Named slots: <slot name="header" />. Scoped slots pass data from child to parent slot content.
Q19. What is defineExpose()?
<script setup> components are "closed" — template refs cannot access their internals. defineExpose({ count, increment }) explicitly exposes specific properties for parent access via template refs.
Q20. What are Vue directives?
Special attributes (v- prefix) that apply reactive behavior to DOM elements. Built-in: v-if, v-for, v-bind, v-model, v-on. Custom directives: const vFocus = { mounted: (el) => el.focus() }.
Q21. What is v-memo?
Directive that memoizes a template sub-tree. v-memo="[dep1, dep2]" skips re-render of that block if listed dependencies haven't changed. Useful for large v-for lists.
Q22. What is <KeepAlive>?
Wrapper that caches component state instead of destroying it when the component is conditionally removed. onActivated/onDeactivated hooks fire instead of onMounted/onUnmounted.
Q23. What is <Teleport>?
Renders a component's template in a different DOM location, such as <body> or #modal-container. Perfect for modals, toasts, and tooltips that need to escape overflow:hidden containers.
Q24. What is <Suspense>?
Built-in component for handling async component loading declaratively. Shows #fallback slot while async component loads, then swaps to #default when ready.
Q25. What is the difference between shallowRef and ref?
ref is deeply reactive — nested property changes trigger updates. shallowRef is only reactive at the top level — replacing .value triggers update, mutating nested properties does NOT without triggerRef().
Q26. What is watchEffect?
Like watch but automatically tracks all reactive dependencies accessed inside the function. Runs immediately on creation, then re-runs when any dependency changes. No need to specify sources.
Q27. What are navigation guards in Vue Router?
Middleware functions that run before route changes. Global: router.beforeEach. Per-route: beforeEnter. In-component: onBeforeRouteLeave, onBeforeRouteUpdate. Used for auth, permission checks, unsaved changes warnings.
Q28. How do you implement lazy loading in Vue?
Routes: component: () => import('./View.vue'). Components: defineAsyncComponent(() => import('./Heavy.vue')). Both create separate JS chunks downloaded only when needed.
Q29. What is the key attribute in v-for?
Helps Vue's virtual DOM differ algorithm identify which items changed/moved/removed. Must be unique and stable (use item ID, not index). Without keys, Vue may incorrectly reuse DOM nodes.
Q30. How does Vue handle reactivity in arrays?
Vue 3 wraps arrays in Proxy, so all mutating methods (push, pop, splice, sort, reverse, shift, unshift) trigger reactive updates. Replacing the array also works.
---
Section C: Advanced (Q31–40)
Q31. What is FLIP animation in Vue?
First-Last-Invert-Play technique used by <TransitionGroup>. When list items reorder, Vue calculates the difference in positions and animates items from their old position to new position using CSS transforms.
Q32. What is the Vue 3 compiler?
Transforms .vue templates into optimized render functions at build time. Marks "static" parts of templates as hoisted — these never need re-rendering. Dynamic parts get "patch flags" so Vue updates only changed DOM nodes.
Q33. What is tree-shaking in Vue 3?
Vue 3 is fully modular — you import { ref, computed } only what you use. Unused Vue APIs are excluded from the production bundle. Vue 2's Options API always included everything.
Q34. How does Vue handle SSR (Server-Side Rendering)?
Nuxt.js adds SSR to Vue. Components render to HTML strings on the server (for SEO/FCP), then "hydrate" in the browser (attach event listeners to server-rendered HTML). useNuxtApp, useFetch, useState replace Vue's client-only hooks.
Q35. What is the inject/provide pattern's limitation?
Works only top-down (parent to child/grandchild). Cannot inject from sibling or child to parent. For bidirectional communication, use Pinia store.
Q36. How do you handle errors in Vue 3?
onErrorCaptured(err, component, info) in parent components. app.config.errorHandler globally. useRouter().afterEach() for routing errors. Wrapping async code in try/catch within composables.
Q37. What are Vue's render functions?
Alternative to templates. h(component, props, children) creates virtual DOM nodes programmatically. More flexible than templates but less readable — use for dynamic component generation or utility components.
Q38. What is Vue's defineModel() macro (Vue 3.4+)?
Simplifies custom v-model. Instead of defineProps({ modelValue }) + defineEmits(['update:modelValue']) + manual emit, use const model = defineModel() and bind directly.
Q39. What are Vue plugins?
Objects with install(app, options) methods registered via app.use(). Used to add global functionality: components, directives, mixins, or provide values globally.
Q40. What is Vue's virtual DOM? An in-memory JavaScript representation of the DOM. Vue compares old and new virtual DOM trees (diffing) and applies only the minimum necessary changes to the real DOM (patching).
---
Section D: Coding Challenges (Q41–50 + 20 exercises)
Q41. Implement useDebounce(value, delay) composable.
Q42. Write a useLocalStorage(key, default) composable.
Q43. Create a BaseModal component with open/close via slot and emit.
Q44. Build a usePagination composable with page, totalPages, next, prev.
Q45. Write a v-focus custom directive.
Q46. Implement optimistic UI delete with rollback in a Vue component.
Q47. Create a Pinia auth store with login, logout, and token persistence.
Q48. Write a useIntersectionObserver composable for infinite scroll.
Q49. Build a type-safe defineProps with validator for a rating component.
Q50. Implement onBeforeRouteLeave for unsaved form changes.
20 Coding Exercises
- 1. Counter with min/max/step/reset
- 2. Todo with filter/sort/search
- 3. Filterable product grid
- 4. Registration form with validation
- 5. Multi-step form wizard
- 6. Infinite scroll list
- 7. Drag and drop sortable list
- 8. Real-time search (debounced API)
- 9. Dark/light mode toggle with persistence
- 10. Shopping cart with Pinia
- 11. Auth login flow with route guard
- 12. Dynamic route params user profile
- 13. Animated tab switcher
- 14. File upload with progress
- 15. Paginated data table
- 16. Custom v-model select component
- 17. Chat UI with mock messages
- 18. Dashboard with stat cards
- 19. Blog post CRUD with API
- 20. Fully responsive landing page