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. 1. How does Vue 3 track reactive dependencies?

    Correct answer: Proxy get traps record subscribers, set traps notify them

    Effects (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. 2. Why is reactive(obj) === obj false, and why does it matter?

    Correct answer: It returns a Proxy, and writing to the original skips tracking

    Always work with the proxy. Calling reactive on the same object returns the same proxy, and toRaw(proxy) gives back the original when you need untracked access.

  3. 3. When should you use markRaw on 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. markRaw tells Vue never to convert the object.

  4. 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. 5. What is effectScope for?

    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. 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 when count goes from 2 to 4. Returning a new object each time still defeats this.

  7. 7. What goes wrong when a lifecycle hook is registered after await in a plain setup() 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, watch and inject rely on the active instance, which is only set during synchronous setup. Register them before the first await, or use <script setup>, whose compiler preserves the context.

  8. 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 effectScope

    Each normal call creates new state and listeners. VueUse's createSharedComposable counts subscribers and stops the scope when the last component unmounts.

  9. 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 class or text can change. Block trees flatten dynamic nodes so the diff skips static structure entirely.

  10. 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. 11. What goes wrong when v-for uses the index as key and 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. 12. How can changing the key of 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. 13. What does v-memo do?

    <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-once renders once and never updates; v-memo is the conditional version.

  14. 14. Why can passing activeId to 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 activeId changes

    Child components update when any prop changes. Keeping props stable means only the two items whose active flag flips will re-render.

  15. 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. 16. Why might wrapping large API data in reactive/ref be costly, and what is the alternative?

    Correct answer: Deep reactivity proxies nested objects; use shallowRef

    Deep proxies add overhead on access and tracking. For large read-mostly data, shallow reactivity plus replacing the whole value keeps updates cheap.

  17. 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. 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. 19. Why does <KeepAlive> without max risk memory growth?

    Correct answer: Every visited instance stays cached with its DOM

    max turns the cache into an LRU. Use include to cache only views where preserving state actually helps (e.g. a filtered list the user returns to).

  20. 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. 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 onMounted or <ClientOnly> (Nuxt). Vue 3.5 adds data-allow-mismatch to silence expected differences such as timestamps.

  22. 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, hydrateOnInteraction and hydrateOnMediaQuery. The HTML is visible immediately, but JS for below-the-fold parts loads later.

  23. 23. Why use useId() (3.5+) for id/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. useId ties the ID to the component's position in the tree.

  24. 24. Which lifecycle hooks run during SSR?

    Correct answer: Only setup code and onServerPrefetch

    Avoid side effects in setup that need cleanup (timers, subscriptions) - onUnmounted never runs on the server, so they leak. Put them in onMounted.

  25. 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/useAsyncData fetch on the server and transfer the result in the payload, so the client doesn't refetch during hydration.

  26. 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. 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 execute

    Never 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. 28. Is binding a user-provided URL to :href safe in Vue?

    Correct answer: No: Vue doesn't sanitize javascript: URLs

    Escaping prevents breaking out of the attribute, not malicious schemes. Validate that the URL starts with https:// or is relative before storing it.

  29. 29. Why is binding user-controlled values to :style risky?

    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. 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. 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. 32. Which Vue 2 patterns must be replaced when migrating to Vue 3?

    Correct answer: Global Vue.* APIs, the $on event bus and filters

    Other changes: component v-model uses modelValue/update:modelValue, $listeners merged into $attrs, and multiple root nodes are allowed. Vue 2 reached end of life at the end of 2023.

  33. 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. 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 defineCustomElement

    Styles are injected into the shadow root. Props map to attributes/properties and emitted events become CustomEvents. Useful for embeddable widgets.

  35. 35. What does a global app.config.errorHandler give you that onErrorCaptured doesn't?

    Correct answer: One place to report all uncaught errors to monitoring

    Use onErrorCaptured for local error boundaries with fallback UI, and the global handler (or Sentry's Vue integration) for reporting.

  36. 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 generic attribute 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. 37. What does defineSlots add?

    defineSlots<{
      default(props: { item: User }): any;
      empty(): any;
    }>();

    Correct answer: Type checking for slot names and scoped slot props

    Without it, slot props are any in the parent. It is type-only and compiled away.

  38. 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 null before mount, hence optional chaining. Prefer props/events over calling child methods; exposing methods is for imperative APIs like focus() or open().

  39. 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.matched so meta from parent routes applies to their children too

    to.meta is a shallow merge of parent and child meta, so child values overwrite parent ones; to.matched gives each level separately. Type meta via RouteMeta module augmentation.

  40. 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 scrollBehavior option of the router

    saved is provided only for popstate navigations. You can also scroll to to.hash or return a Promise to wait for async content.

  41. 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. removeRoute deletes it.

  42. 42. How do guards handle async work like fetching permissions?

    Correct answer: Guards can be async, and navigation waits for them

    Keep guards fast or cache results - every navigation waits. The older next() callback style is still supported but returning values is recommended.

  43. 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 PiniaCustomProperties augmentation.

  44. 44. What is the difference between $subscribe and a watch on store state?

    Correct answer: $subscribe fires once per $patch, with mutation info

    Subscriptions added inside a component are removed when it unmounts unless detached is set. $onAction is the equivalent for actions.

  45. 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. 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; provide values can be passed via global.provide in Vue Test Utils.

  47. 47. How do you test a component that uses Vue Router?

    Correct answer: Install a real router with createMemoryHistory

    Memory history works in Node. Alternatively stub RouterLink and mock useRoute for isolated tests; real routers catch more integration bugs.

  48. 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. 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. 50. What does createRenderer from @vue/runtime-core allow?

    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. 51. What does the previous argument 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. 52. What does deep: 2 on 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. 53. How do you type a global property like $t added with app.config.globalProperties?

    declare module 'vue' {
      interface ComponentCustomProperties {
        $t: (key: string) => string
      }
    }

    Correct answer: Augment ComponentCustomProperties in vue

    Global properties are mainly for templates and the Options API; in <script setup> prefer provide/inject or a composable.

  54. 54. How do you stream SSR HTML to the client instead of waiting for the whole page?

    Correct answer: Use renderToWebStream or renderToNodeStream

    The browser can start parsing earlier, improving time to first byte. Headers and status must be decided before streaming starts.

  55. 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. 56. What is onServerPrefetch for?

    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. 57. Why does Nuxt warn against calling $fetch directly 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. $fetch is fine in event handlers.

  58. 58. Why use Nuxt's useState instead of a module-level ref for 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. 59. When is router.beforeResolve the 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. afterEach can't cancel navigation.

  60. 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 false or a route location

    Returning values avoids bugs like calling next() twice or never. Guards can also be async functions.

  61. 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-slot of <RouterView>

    Vue Router 4 removed the old wrapper pattern; the slot gives full control over the order of wrappers.

  62. 62. What is skipHydrate in 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. 63. Why add acceptHMRUpdate to 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. 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. 65. What does returning false from onErrorCaptured do?

    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. 66. How do you mock API calls in component tests without mocking fetch per 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. 67. How do you build a Vue component library with Vite without bundling Vue itself?

    Correct answer: Use library mode with vue as external

    Bundling Vue would create two Vue instances in the consumer app, breaking reactivity and provide/inject.

  68. 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 type checks only the constructor (Object); PropType gives TypeScript the exact shape.

  69. 69. Why is a global app.provide() often better than globalProperties for app-wide services?

    Correct answer: Injected values are explicit, typed and easy to override

    globalProperties are implicit this additions mostly suited to the Options API.

  70. 70. How are <Teleport> contents handled in SSR?

    Correct answer: They're collected in the context's teleports

    Frameworks like Nuxt do this automatically; hand-rolled SSR must handle it, or hydration of modals fails.

  71. 71. Why can a reactive array of 50,000 objects make filtering slow, and what helps?

    Correct answer: Each access is tracked; shallowRef avoids deep tracking

    Read-only data rarely needs deep reactivity. markRaw objects or shallowRef cut overhead dramatically.

  72. 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 ref

    Later prop changes won't update the copy; if they should, watch the prop or use defineModel instead.

  73. 73. How do micro-frontends share one Vue runtime with Module Federation?

    Correct answer: Declare vue as a shared singleton

    Multiple Vue copies break provide/inject, devtools and memory. Version ranges must be compatible.

  74. 74. When does a component with an async setup() need special care in tests?

    Correct answer: It must be wrapped in <Suspense> before assertions

    Test helpers often mount a wrapper with <Suspense> and then wait for promises to resolve.

  75. 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.