Vue Junior 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. What is Vue?

    Correct answer: A progressive JavaScript framework for building UIs

    "Progressive" means you can start by enhancing a single page with Vue and grow to a full SPA with routing (Vue Router), state management (Pinia) and SSR (Nuxt). The core library focuses on the view layer and reactivity.

  2. 2. What is the recommended way to scaffold a new Vue project?

    Correct answer: npm create vue@latest

    create-vue sets up a Vite-based project and optionally adds TypeScript, Vue Router, Pinia, Vitest, ESLint and end-to-end testing. The old Vue CLI (webpack-based) is in maintenance mode.

  3. 3. What does a Single-File Component (.vue file) contain?

    <script setup>
    import { ref } from "vue";
    const count = ref(0);
    </script>
    
    <template>
      <button @click="count++">Clicked {{ count }} times</button>
    </template>
    
    <style scoped>
    button { font-weight: bold; }
    </style>

    Correct answer: The component's logic, template and styles in one file

    SFCs keep related code together. The build tool (Vite plugin) compiles <template> into a render function, processes <script setup> and scopes the styles.

  4. 4. How is a Vue application created and attached to the page?

    import { createApp } from "vue";
    import App from "./App.vue";
    
    createApp(App).mount("#app");

    Correct answer: createApp(rootComponent), then .mount() on a selector

    Plugins are registered on the app instance before mounting: createApp(App).use(router).use(createPinia()).mount('#app'). new Vue() was the Vue 2 API.

  5. 5. What is the difference between the Options API and the Composition API?

    Correct answer: Options API groups code by option type, Composition API by feature

    Both are supported in Vue 3. The Composition API (usually via <script setup>) makes logic reuse with composables and TypeScript inference easier; the Options API is still fine for simpler components.

  6. 6. What does {{ message }} do in a Vue template?

    Correct answer: Renders the value as escaped text and keeps it updated

    Mustache syntax outputs plain text, so it is safe from XSS. To render HTML you need v-html, which should never receive untrusted content.

  7. 7. How do you bind an attribute to a JavaScript value?

    Correct answer: v-bind:href="url" or just :href

    Mustaches don't work in attributes. :disabled="isSaving" passes a boolean, and since Vue 3.4 :href="href" can be shortened to :href when the variable has the same name.

  8. 8. How do you listen to a click?

    Correct answer: @click="save" or v-on:click

    The handler can be a method name (@click="save") or an inline statement (@click="count++"). The native event is available as $event in inline handlers.

  9. 9. What does @submit.prevent="onSubmit" do?

    Correct answer: Calls onSubmit and also event.preventDefault()

    Event modifiers keep handlers focused on logic: .prevent, .stop, .once, .self, .capture, .passive. Key modifiers such as @keyup.enter filter keyboard events.

  10. 10. How do you toggle a CSS class based on a condition?

    Correct answer: :class="{ active: isActive }"

    :class accepts an object, an array or a string, and is merged with a static class attribute. :style works similarly with objects like { color: textColor }.

  11. 11. Which expressions are allowed inside template bindings?

    Correct answer: Single JavaScript expressions, not statements

    Each binding must evaluate to a value. Complex logic belongs in a computed property or a function in <script setup>.

  12. 12. What does the shorthand # mean in <template #header>?

    Correct answer: It is short for v-slot:header

    Vue has three common shorthands: : for v-bind, @ for v-on and # for v-slot.

  13. 13. How do you declare reactive state in <script setup>?

    const count = ref(0);
    function increment() {
      count.value++;
    }

    Correct answer: With ref(), and .value in JavaScript

    ref wraps a value in an object with a reactive .value property. Top-level refs are automatically unwrapped in templates, so you write {{ count }}.

  14. 14. What does reactive() return?

    const state = reactive({ count: 0, user: { name: "Ann" } });
    state.count++;

    Correct answer: A deeply reactive Proxy of the object

    reactive only works with objects, arrays and collections - not primitives. The Vue docs recommend ref as the primary API because it works with any value type.

  15. 15. Why does destructuring a reactive object break reactivity?

    const state = reactive({ count: 0 });
    let { count } = state;
    count++; // the UI doesn't update

    Correct answer: It copies the primitive value out of the Proxy

    Reactivity works through property access on the Proxy. Use toRefs(state) to destructure into refs that stay connected, or use ref from the start.

  16. 16. What is computed() for?

    const firstName = ref("Ann");
    const lastName = ref("Lee");
    const fullName = computed(() => `${firstName.value} ${lastName.value}`);

    Correct answer: A cached value recalculated when its dependencies change

    A method called in the template runs on every re-render; a computed property returns the cached result until firstName or lastName changes. Computed getters should be free of side effects.

  17. 17. Why might the DOM not be updated immediately after changing state?

    Correct answer: Vue batches updates and applies them in the next tick

    Changing state several times in a row results in a single DOM update. If you need to measure the updated DOM, call await nextTick() after the change.

  18. 18. Do you need .value when using a ref in the template?

    Correct answer: No, top-level refs are auto-unwrapped

    Unwrapping applies to top-level properties of the template context. A ref nested inside a plain object ({{ obj.count }}) is not unwrapped and would need .value.

  19. 19. Can you assign a new array to a ref holding a list?

    const items = ref([]);
    items.value = await fetchItems();

    Correct answer: Yes: replacing .value is tracked

    Vue 3's Proxy-based reactivity tracks both replacing the value and mutating arrays (push, splice, index assignment). This was a known limitation in Vue 2 that is gone now.

  20. 20. What is the difference between v-if and v-show?

    Correct answer: v-if adds or removes the element, v-show toggles CSS

    v-if has a higher toggle cost but nothing is rendered while false; v-show has a higher initial cost but cheap toggling. Use v-show for elements that toggle often.

  21. 21. Which directives form a chain of conditions?

    <p v-if="type === 'A'">A</p>
    <p v-else-if="type === 'B'">B</p>
    <p v-else>Other</p>

    Correct answer: v-if, v-else-if and v-else

    The v-else-if and v-else elements must immediately follow a v-if or v-else-if element. Wrap several elements in <template v-if> to toggle them as a group.

  22. 22. How do you render a list?

    <li v-for="todo in todos" :key="todo.id">{{ todo.text }}</li>

    Correct answer: With v-for and a unique :key per item

    The key helps Vue match items between renders so it can reuse and reorder DOM nodes and keep component state attached to the correct item. Use a stable id, not the index, for dynamic lists.

  23. 23. How do you get the index in v-for?

    Correct answer: v-for="(item, index) in items"

    For objects the syntax is (value, key, index) in object. v-for can also iterate a range: v-for="n in 10" renders 1 to 10.

  24. 24. Why shouldn't v-if and v-for be used on the same element?

    Correct answer: In Vue 3 v-if runs first and can't see the loop variable

    To show only some items, use a computed property like activeTodos. To hide the whole list, put v-if on a wrapper element or <template>.

  25. 25. What does v-model on an input do?

    <input v-model="name" />
    <p>Hello, {{ name }}</p>

    Correct answer: Two-way binding between the input and the state

    On a text input v-model is sugar for :value="name" @input="name = $event.target.value". For checkboxes, radios and selects Vue uses the right property and event automatically.

  26. 26. What does v-model.number do?

    Correct answer: Converts the input value to a number when possible

    Input values are always strings. Other modifiers: .trim removes whitespace and .lazy syncs on change instead of input.

  27. 27. How does v-model work with several checkboxes bound to one array?

    <input type="checkbox" value="vue" v-model="skills" />
    <input type="checkbox" value="react" v-model="skills" />

    Correct answer: Checked values are added to skills, unchecked removed

    With an array, Vue adds or removes each checkbox's value. With a single checkbox bound to a boolean, it toggles true/false (or custom true-value/false-value).

  28. 28. How does a child component declare the props it accepts in <script setup>?

    <script setup>
    const props = defineProps({ title: String, likes: Number });
    </script>

    Correct answer: With the defineProps() compiler macro, which doesn't need to be imported

    defineProps and defineEmits are compiled away by the SFC compiler. With TypeScript you can declare props by type: defineProps<{ title: string }>().

  29. 29. Why shouldn't a child mutate a prop?

    Correct answer: Data flows one way: the parent owns the value

    If the child needs to change the value, emit an event so the parent updates it, or copy the prop into local state if it's only an initial value.

  30. 30. How does a child notify its parent?

    <script setup>
    const emit = defineEmits(["save"]);
    function onClick() { emit("save", { id: 1 }); }
    </script>
    <!-- parent: <Editor @save="handleSave" /> -->

    Correct answer: By emitting an event with defineEmits

    The parent listens with @save, and the payload becomes the handler argument. Unlike native DOM events, component events don't bubble.

  31. 31. How do you pass markup from a parent into a child component?

    <!-- Card.vue -->
    <div class="card"><slot /></div>
    
    <!-- usage -->
    <Card><p>Any content</p></Card>

    Correct answer: With slots: the child renders <slot />

    Content between <slot> tags is the fallback when the parent passes nothing. Named slots (<slot name="header" />) allow several insertion points.

  32. 32. How do you use a child component in <script setup>?

    <script setup>
    import UserCard from "./UserCard.vue";
    </script>
    <template><UserCard name="Ann" /></template>

    Correct answer: Import it; imported components are available in the template automatically

    With <script setup> there is no separate registration step. Global registration via app.component() also works but prevents tree-shaking and hides dependencies.

  33. 33. What happens to attributes like class passed to a component that doesn't declare them as props?

    <MyButton class="large" data-test="save" />

    Correct answer: They fall through to the root element

    Fallthrough attributes (including listeners like @click) are applied to the single root element; class and style are merged. Use inheritAttrs: false with v-bind="$attrs" to move them elsewhere.

  34. 34. What does <style scoped> do?

    Correct answer: Limits the styles to this component with data-v-*

    The compiler rewrites .btn to .btn[data-v-7ba5bd90]. A child component's root element is affected by both the parent's and its own scoped styles; to style deeper elements use :deep().

  35. 35. How does a parent use v-model on a custom component (Vue 3.4+)?

    <!-- Child.vue -->
    <script setup>
    const model = defineModel();
    </script>
    <template><input v-model="model" /></template>
    
    <!-- parent: <Child v-model="text" /> -->

    Correct answer: With defineModel(), which returns a ref synced with the parent's v-model

    defineModel declares a modelValue prop and an update:modelValue event under the hood. Named models are supported too: v-model:title with defineModel('title').

  36. 36. How do you give a prop a default value and make another one required?

    defineProps({
      title: { type: String, required: true },
      size: { type: String, default: "md" },
    });

    Correct answer: Object syntax: required: true and default

    Vue warns in development when a required prop is missing or has the wrong type. For object or array defaults use a factory function: default: () => [].

  37. 37. How do you switch between several components dynamically?

    <component :is="tabs[current]" />

    Correct answer: With the built-in <component :is="..."> element

    :is accepts an imported component or a registered component name. When switching, the old component is unmounted unless it is wrapped in <KeepAlive>.

  38. 38. How can a deeply nested component receive a value without passing props through every level?

    // ancestor
    provide("theme", theme);
    // any descendant
    const theme = inject("theme");

    Correct answer: provide in an ancestor, inject in the descendant

    provide/inject avoids prop drilling. If you provide a ref, the injected value stays reactive. For app-wide state, Pinia is usually a better fit.

  39. 39. Why is v-html dangerous?

    <div v-html="comment.body"></div>

    Correct answer: It inserts raw HTML, so user content can run scripts

    Vue escapes {{ }} output, but v-html bypasses that. Only use it with trusted content or HTML sanitized by a library such as DOMPurify.

  40. 40. Where should you access the DOM after the component is rendered?

    Correct answer: In onMounted

    <script setup> runs before the component is mounted, so the DOM doesn't exist yet. onMounted runs after the first render; it is also never called during SSR.

  41. 41. What is onUnmounted used for?

    Correct answer: Cleaning up timers, listeners and subscriptions

    Anything set up manually in onMounted (setInterval, addEventListener) must be torn down in onUnmounted, or it keeps running and leaks memory.

  42. 42. When should you use watch instead of computed?

    Correct answer: When a change must trigger a side effect

    computed returns a derived value; watch runs code. watch(id, async (newId) => { data.value = await load(newId) }) is a typical use.

  43. 43. How do you get a reference to a DOM element in <script setup> (Vue 3.5+)?

    <script setup>
    import { useTemplateRef, onMounted } from "vue";
    const input = useTemplateRef("search");
    onMounted(() => input.value.focus());
    </script>
    <template><input ref="search" /></template>

    Correct answer: With useTemplateRef('name')

    Before 3.5 you declared const search = ref(null) with the same name as the ref attribute. The value is null until the element is mounted.

  44. 44. Where does Vue Router render the component for the current URL?

    Correct answer: In <RouterView />

    <RouterView> is a placeholder in the layout. Nested routes render in a nested <RouterView> inside the parent route component.

  45. 45. How do you create a navigation link without reloading the page?

    Correct answer: <RouterLink to="/about">About</RouterLink>

    RouterLink renders an <a> with the correct href, handles the click on the client and adds active classes (router-link-active).

  46. 46. How do you read the :id param of the route /users/:id in <script setup>?

    Correct answer: useRoute().params.id

    useRoute() returns the reactive current route (params, query, hash). useRouter() returns the router instance for navigation.

  47. 47. How do you navigate from code, e.g. after saving a form?

    Correct answer: const router = useRouter(); router.push('/users/' + id)

    router.push adds a history entry, router.replace replaces the current one and router.back() goes back. Both accept strings or objects like { name: 'user', params: { id } }.

  48. 48. What is Pinia?

    Correct answer: The official state management library for Vue

    Pinia has a simpler API than Vuex (no mutations), full TypeScript support and devtools integration. Vuex is in maintenance mode.

  49. 49. How is a Pinia store defined and used?

    export const useCounterStore = defineStore("counter", () => {
      const count = ref(0);
      const double = computed(() => count.value * 2);
      function increment() { count.value++; }
      return { count, double, increment };
    });
    // in a component: const counter = useCounterStore();

    Correct answer: With defineStore, using refs, computed and functions

    This is a setup store; there are also option stores with state, getters and actions. The store is created on first use and shared across components.

  50. 50. What do you need to do before using any Pinia store?

    Correct answer: Install the plugin: app.use(createPinia())

    Calling a store hook before the Pinia instance is installed throws an error about no active Pinia. In SSR a new Pinia instance is created for each request.

  51. 51. What do the .stop and .once event modifiers do?

    <button @click.stop="select">Select</button>
    <button @click.once="subscribe">Subscribe</button>

    Correct answer: .stop stops propagation, .once fires only the first time

    Modifiers keep handlers focused on logic instead of DOM details. Others include .prevent, .self, .capture and .passive.

  52. 52. How do you run a handler only when Enter is pressed in an input?

    <input @keyup.enter="search" />

    Correct answer: Use the key modifier @keyup.enter

    Vue provides aliases like .enter, .esc, .tab, .space and system modifiers like .ctrl or .exact.

  53. 53. What does v-model.trim do?

    Correct answer: Removes leading and trailing whitespace

    Modifiers can be combined, e.g. v-model.trim.lazy. The DOM value may still show spaces while typing.

  54. 54. What does v-model.lazy change?

    Correct answer: The value syncs on change instead of input

    It reduces updates while the user types - useful when every change triggers expensive work.

  55. 55. How do you bind several inline styles from an object?

    <div :style="{ color: textColor, fontSize: size + 'px' }"></div>

    Correct answer: Bind :style to an object of properties

    :style also accepts an array of objects. Vue adds vendor prefixes when needed.

  56. 56. What does v-bind="attrs" without an argument do?

    const attrs = { id: 'email', type: 'email', required: true }
    <input v-bind="attrs" />

    Correct answer: Binds every property of the object as a separate attribute

    It's handy for passing a group of props or attributes to a component without listing them one by one.

  57. 57. What does v-once do?

    Correct answer: Renders the element once, then skips it in updates

    Static content no longer re-renders when data changes, which can save work for large static parts.

  58. 58. What does <li v-for="n in 3">{{ n }}</li> render?

    Correct answer: 1, 2, 3

    v-for with a number repeats the template that many times, starting from 1, unlike array indices.

  59. 59. How do you iterate over an object's properties?

    <li v-for="(value, key) in user" :key="key">{{ key }}: {{ value }}</li>

    Correct answer: v-for="(value, key) in object"

    A third alias gives the index: (value, key, index). The order follows Object.keys().

  60. 60. How do you apply v-if to several elements without adding a wrapper <div>?

    <template v-if="loggedIn">
      <h1>Welcome</h1>
      <p>You have new messages</p>
    </template>

    Correct answer: Put v-if on an invisible <template>

    <template> isn't rendered in the final DOM. It also works with v-for and v-else.

  61. 61. Why does v-for need a unique :key?

    Correct answer: So Vue can track each item and reuse the right nodes

    Use a stable id from the data. Without keys, Vue patches in place, which can mix up inputs or component state when the order changes.

  62. 62. How do you pass both an argument and the native event to a handler?

    <button @click="remove(item.id, $event)">Delete</button>

    Correct answer: Use an inline handler and the special $event variable

    An inline arrow function also works: @click="(e) => remove(item.id, e)".

  63. 63. How should a prop declared as userName be written in a parent template?

    Correct answer: user-name="...", by convention

    Props are declared in camelCase in JavaScript, and kebab-case in templates matches HTML attribute conventions.

  64. 64. What value does a Boolean prop get with <MyButton disabled />?

    Correct answer: true

    Vue casts the presence of the attribute to true, like native boolean attributes. Without the attribute it's false.

  65. 65. How does the parent receive the value sent with emit('select', id)?

    <ItemList @select="onSelect" />
    
    function onSelect(id) { /* ... */ }

    Correct answer: As the handler's argument

    Extra arguments of emit are passed to the listener. In an inline handler the first one is available as $event.

  66. 66. How do you show default content when the parent passes nothing to a slot?

    <button><slot>Submit</slot></button>

    Correct answer: Put fallback content inside <slot>

    The fallback is rendered only if the parent provides no content for that slot.

  67. 67. How do you navigate to a route by its name?

    router.push({ name: 'user', params: { id: 42 } })

    Correct answer: Pass name and params to router.push

    Named routes don't break when the URL path changes, and params are encoded automatically.

  68. 68. Which classes does <RouterLink> add to an active link by default?

    Correct answer: router-link-active, router-link-exact-active

    The class names can be changed per link (active-class) or globally in createRouter.

  69. 69. How do you make / open /home?

    { path: '/', redirect: '/home' }

    Correct answer: Add a route with redirect

    The URL changes to /home. An alias instead keeps the original URL while showing the same component.

  70. 70. How do you define a catch-all 404 route in Vue Router 4?

    { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }

    Correct answer: path: '/:pathMatch(.*)*'

    The old * syntax from Vue Router 3 was removed. Matched segments are available in route.params.pathMatch.

  71. 71. What is a getter in a Pinia store?

    Correct answer: A cached derived value, like computed

    In setup stores getters are simply computed() values. Put async work and mutations into actions.

  72. 72. What is Vue DevTools used for?

    Correct answer: Inspecting components, state, stores and routes

    It's available as a browser extension and a Vite plugin. It works with development builds of Vue.

  73. 73. Which environment variables are exposed to client code in a Vite project?

    const api = import.meta.env.VITE_API_URL

    Correct answer: Only variables prefixed with VITE_

    Values are embedded at build time and are public. Never put secrets into VITE_ variables.

  74. 74. Which is the recommended default for reactive state in the Composition API?

    Correct answer: ref(), as it works with any value type

    The Vue docs recommend ref as the primary API because reactive only works with objects and loses reactivity on destructuring or replacement.

  75. 75. Why can a ref declared with const still change?

    const count = ref(0)
    count.value++ // works

    Correct answer: const only blocks reassigning the variable itself

    Writing count = ref(1) would fail and also break every place that holds the old ref. Use readonly() to make a value truly read-only.