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. 1. Why doesn't this watcher fire?

    const state = reactive({ count: 0 });
    watch(state.count, (n) => console.log(n));

    Correct answer: state.count is a plain number here; watch a getter instead

    watch accepts 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. 2. How does watchEffect differ from watch?

    Correct answer: watchEffect runs at once and tracks what it reads; watch is lazy

    watchEffect is concise when the effect uses the same state it depends on. watch gives precise control: only listed sources trigger it, and it can be immediate or once.

  3. 3. How do you cancel a stale request when a watched id changes 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 onWatcherCleanup

    Without cleanup, a slow old response can overwrite newer data. Before 3.5 the same was done with the onCleanup argument of the callback.

  4. 4. What does { deep: true } do on a watcher?

    Correct answer: Fires on nested mutations inside the watched object

    Watching a reactive object 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. 5. When is shallowRef a better choice than ref?

    Correct answer: For large data that only changes by replacing .value

    ref makes nested objects deeply reactive via Proxies, which costs time for huge structures. shallowRef tracks only .value replacement; use triggerRef if you mutate and need to force an update.

  6. 6. What does toRefs do?

    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. 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-model on derived values; the getter still must be pure.

  8. 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. 9. How do you make a watch callback also run right away with the current value?

    watch(() => route.params.id, loadUser, { immediate: true });

    Correct answer: Pass { immediate: true }

    By default watch is lazy and fires only on changes. immediate runs it once on creation; { once: true } (3.4+) stops it after the first trigger.

  10. 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' (or watchPostEffect) is for reading layout; flush: 'sync' runs immediately on every change and should be rare.

  11. 11. What do defineModel modifiers 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 defineModel gives the ref and the modifiers object. get/set options transform values in both directions.

  12. 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 inheritAttrs and bind $attrs to the element

    This is common for wrapped inputs: placeholder, aria-* and @input should reach the <input>, not the wrapper. Components with multiple roots must bind $attrs explicitly.

  13. 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. 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 readonly version plus a function for changes

    Keeping mutations in the provider keeps the data flow traceable. Descendants that need to change state call the provided function.

  15. 15. Why use an InjectionKey symbol instead of a string for provide/inject?

    export const ThemeKey: InjectionKey<Ref<string>> = Symbol("theme");
    provide(ThemeKey, theme);
    const t = inject(ThemeKey); // Ref<string> | undefined

    Correct answer: Symbols avoid name collisions and carry the type

    Put keys in a shared file. inject returns T | undefined unless you pass a default value.

  16. 16. What does defineAsyncComponent do?

    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, delay and timeout. Combine with v-if so heavy widgets download only when needed.

  17. 17. What does defineExpose do 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 call childRef.value.focus().

  18. 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 count to props.count. To watch a destructured prop you still need a getter: watch(() => count, ...).

  19. 19. How do you type component events with TypeScript?

    const emit = defineEmits<{
      change: [id: number];
      update: [value: string];
    }>();

    Correct answer: With a type-based defineEmits declaration

    Calling emit('change', 'x') is then a type error, and parents get typed handler arguments. vue-tsc checks templates and SFCs in CI.

  20. 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 in setup, and return refs. VueUse is a large collection of ready-made ones.

  21. 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 x came from and can rename on the fly. Mixins are not recommended in Vue 3.

  22. 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 with toValue()

    Calling toValue inside watchEffect (or a watch getter) tracks the argument, so useFetch(() => /api/${id.value}) re-fetches when id changes.

  23. 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 onUnmounted inside the composable isn't registered and listeners leak. <script setup> restores the instance after a top-level await, so calls after it still work.

  24. 24. What happens when <script setup> contains a top-level await?

    <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 #fallback slot meanwhile. It is still marked experimental, so many teams prefer explicit loading state.

  25. 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, like vFocus

    Directive hooks mirror lifecycle hooks (created, mounted, updated, unmounted). Use directives for low-level DOM access; prefer components for anything with its own markup.

  26. 26. What is a Vue plugin?

    Correct answer: An object with install(), registered with app.use()

    Plugins can register global components and directives, app.provide values or add app.config.globalProperties. Router and Pinia are installed as plugins.

  27. 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/onDeactivated instead of being unmounted. include, exclude and max control what is cached.

  28. 28. Why render a modal with <Teleport to="body">?

    Correct answer: To place its DOM in <body>, out of reach of parent overflow

    Teleport changes only where the DOM goes; props, events and provide/inject still work as if the modal were in place.

  29. 29. How does <Transition name="fade"> animate an element?

    Correct answer: It adds classes like fade-enter-active on enter and leave

    It works with v-if, v-show, dynamic components and key changes. <TransitionGroup> handles lists, including move animations.

  30. 30. What problem does nextTick solve 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.value is still null.

  31. 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 defineAsyncComponent for route components - the router handles it.

  32. 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 beforeEach guard that checks to.meta

    Returning false cancels navigation, returning a route redirects, returning nothing allows it. Real protection must still happen on the server API.

  33. 33. Why doesn't the page update when navigating from /users/1 to /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 }) or onBeforeRouteUpdate. Alternatively force a remount with <RouterView :key="route.fullPath" />.

  34. 34. What does props: true in 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. 35. Why does reloading /about return 404 in production with createWebHistory?

    Correct answer: The server has no such file and must fall back to index.html

    Client-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 /#/about URLs.

  36. 36. What is the difference between router.push and router.replace?

    Correct answer: push adds a history entry, replace swaps the current one

    Use replace for 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. 37. How are nested routes rendered?

    {
      path: "/settings",
      component: SettingsLayout,
      children: [
        { path: "profile", component: Profile },
        { path: "security", component: Security },
      ],
    }

    Correct answer: SettingsLayout has its own <RouterView />

    Child paths without a leading / are relative to the parent. A child with an empty path '' renders at /settings itself.

  38. 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; storeToRefs fixes it

    Plain destructuring copies the current values. storeToRefs skips actions and non-reactive properties, so actions are taken from the store itself.

  39. 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. 40. What does store.$patch offer?

    cart.$patch((state) => {
      state.items.push(item);
      state.updatedAt = Date.now();
    });

    Correct answer: Applies several changes as one grouped mutation

    $patch takes a partial object or a function. Direct assignments (cart.total = 0) also work; $patch is useful for batching and readability.

  41. 41. Can Pinia actions be asynchronous?

    Correct answer: Yes, actions can be async and await API calls

    Unlike Vuex there are no separate mutations; actions change state directly. $onAction lets you observe actions, including when they resolve or fail.

  42. 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 installed

    At 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. 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 (Map or object keyed by id) and read from it.

  44. 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. 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. 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 color changes, so the styles stay in CSS.

  47. 47. How do you catch errors from descendant components?

    Correct answer: With onErrorCaptured in an ancestor

    onErrorCaptured can show a fallback UI and return false to stop propagation. app.config.errorHandler is the place to report errors to monitoring.

  48. 48. Why await user interactions in Vue Test Utils?

    const wrapper = mount(Counter);
    await wrapper.find("button").trigger("click");
    expect(wrapper.text()).toContain("1");

    Correct answer: trigger returns a promise that waits for the DOM update

    DOM updates are asynchronous. Awaiting trigger or setValue (or nextTick) makes assertions see the updated DOM.

  49. 49. How do you test a component that uses Pinia stores?

    Correct answer: Mount it with the createTestingPinia() plugin

    Actions become spies (expect(store.addItem).toHaveBeenCalled()), and initialState seeds the store. Store logic itself is tested separately with setActivePinia(createPinia()).

  50. 50. Which tool type-checks .vue files, including templates, in CI?

    Correct answer: vue-tsc --noEmit

    Plain tsc can't parse SFCs. vue-tsc (from the Vue language tools) checks script and template expressions; Vite itself only transpiles without type-checking.

  51. 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. 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. 53. How do you set component options like inheritAttrs: false in <script setup>?

    defineOptions({ inheritAttrs: false })

    Correct answer: With the defineOptions macro (Vue 3.3+)

    Before 3.3 a separate normal <script> block was needed. defineOptions can also set a component name.

  54. 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 watch

    Sources can be refs, reactive objects or getter functions. A property of a reactive object must be wrapped in a getter.

  55. 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. 56. How do you stop a watcher before the component unmounts?

    const stop = watch(source, callback)
    // later
    stop()

    Correct answer: Call the function that watch returns

    Watchers created synchronously in setup stop automatically on unmount. Watchers created asynchronously must be stopped manually to avoid leaks.

  57. 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 trigger

    customRef gives explicit control over tracking. It can be used with v-model like a normal ref.

  58. 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 .value is tracked; use triggerRef(rows)

    shallowRef skips deep reactivity for performance; you decide when the change is announced.

  59. 59. What does <Suspense> do with a component that has a top-level await in <script setup>?

    Correct answer: Shows #fallback until async dependencies resolve

    Without a <Suspense> ancestor such a component won't render. <Suspense> is still marked experimental.

  60. 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, returning false

    In-component guards know the component's state. Closing the tab needs a separate beforeunload listener.

  61. 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. 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.query and watch it with a getter

    URL state survives reloads and can be shared. Query values are strings (or arrays) and need parsing.

  63. 63. What are named views in Vue Router?

    <RouterView name="sidebar" />
    <RouterView />

    Correct answer: Several <RouterView> outlets on one level

    They suit layouts like a main area plus a sidebar that differ per route.

  64. 64. How does a route alias differ from a redirect?

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

    Navigation can be aborted by a guard, cancelled by a newer navigation or be duplicated; these aren't exceptions.

  66. 66. Does a setup store have $reset() like an option store?

    Correct answer: Not by default: you write your own $reset

    Pinia can't know the initial state of arbitrary refs in a setup function, so it can't generate $reset.

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

    $onAction is also the basis for analytics or undo plugins. It returns a function to unsubscribe.

  68. 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. 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 $style

    Unlike scoped, which adds data attributes, CSS Modules rename classes, making them safe to pass to child components.

  70. 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-selector

    Slot content belongs to the parent's scope, so normal scoped selectors don't match it. :global() escapes scoping entirely.

  71. 71. When is shallowMount useful 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 mount with selected stubs.

  72. 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. 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. 74. How do you run a Vite build with settings from .env.staging?

    Correct answer: vite build --mode staging

    The mode selects which .env.[mode] file is loaded. import.meta.env.MODE contains the current mode.

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