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. 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. What is the recommended way to scaffold a new Vue project?
Correct answer:
npm create vue@latestcreate-vuesets 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. What does a Single-File Component (
.vuefile) 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. 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 selectorPlugins are registered on the app instance before mounting:
createApp(App).use(router).use(createPinia()).mount('#app').new Vue()was the Vue 2 API.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. 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. How do you bind an attribute to a JavaScript value?
Correct answer:
v-bind:href="url"or just:hrefMustaches don't work in attributes.
:disabled="isSaving"passes a boolean, and since Vue 3.4:href="href"can be shortened to:hrefwhen the variable has the same name.8. How do you listen to a click?
Correct answer:
@click="save"orv-on:clickThe handler can be a method name (
@click="save") or an inline statement (@click="count++"). The native event is available as$eventin inline handlers.9. What does
@submit.prevent="onSubmit"do?Correct answer: Calls
onSubmitand alsoevent.preventDefault()Event modifiers keep handlers focused on logic:
.prevent,.stop,.once,.self,.capture,.passive. Key modifiers such as@keyup.enterfilter keyboard events.10. How do you toggle a CSS class based on a condition?
Correct answer:
:class="{ active: isActive }":classaccepts an object, an array or a string, and is merged with a staticclassattribute.:styleworks similarly with objects like{ color: textColor }.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
computedproperty or a function in<script setup>.12. What does the shorthand
#mean in<template #header>?Correct answer: It is short for
v-slot:headerVue has three common shorthands:
:forv-bind,@forv-onand#forv-slot.13. How do you declare reactive state in
<script setup>?const count = ref(0); function increment() { count.value++; }Correct answer: With
ref(), and.valuein JavaScriptrefwraps a value in an object with a reactive.valueproperty. Top-level refs are automatically unwrapped in templates, so you write{{ count }}.14. What does
reactive()return?const state = reactive({ count: 0, user: { name: "Ann" } }); state.count++;Correct answer: A deeply reactive Proxy of the object
reactiveonly works with objects, arrays and collections - not primitives. The Vue docs recommendrefas the primary API because it works with any value type.15. Why does destructuring a
reactiveobject break reactivity?const state = reactive({ count: 0 }); let { count } = state; count++; // the UI doesn't updateCorrect 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 usereffrom the start.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
firstNameorlastNamechanges. Computed getters should be free of side effects.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. Do you need
.valuewhen 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. Can you assign a new array to a
refholding a list?const items = ref([]); items.value = await fetchItems();Correct answer: Yes: replacing
.valueis trackedVue 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. What is the difference between
v-ifandv-show?Correct answer:
v-ifadds or removes the element,v-showtoggles CSSv-ifhas a higher toggle cost but nothing is rendered while false;v-showhas a higher initial cost but cheap toggling. Usev-showfor elements that toggle often.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-ifandv-elseThe
v-else-ifandv-elseelements must immediately follow av-iforv-else-ifelement. Wrap several elements in<template v-if>to toggle them as a group.22. How do you render a list?
<li v-for="todo in todos" :key="todo.id">{{ todo.text }}</li>Correct answer: With
v-forand a unique:keyper itemThe
keyhelps 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. 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-forcan also iterate a range:v-for="n in 10"renders 1 to 10.24. Why shouldn't
v-ifandv-forbe used on the same element?Correct answer: In Vue 3
v-ifruns first and can't see the loop variableTo show only some items, use a computed property like
activeTodos. To hide the whole list, putv-ifon a wrapper element or<template>.25. What does
v-modelon 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-modelis sugar for:value="name" @input="name = $event.target.value". For checkboxes, radios and selects Vue uses the right property and event automatically.26. What does
v-model.numberdo?Correct answer: Converts the input value to a number when possible
Input values are always strings. Other modifiers:
.trimremoves whitespace and.lazysyncs onchangeinstead ofinput.27. How does
v-modelwork 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 removedWith an array, Vue adds or removes each checkbox's
value. With a single checkbox bound to a boolean, it togglestrue/false(or customtrue-value/false-value).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 importeddefinePropsanddefineEmitsare compiled away by the SFC compiler. With TypeScript you can declare props by type:defineProps<{ title: string }>().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. 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
defineEmitsThe parent listens with
@save, and the payload becomes the handler argument. Unlike native DOM events, component events don't bubble.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. 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 viaapp.component()also works but prevents tree-shaking and hides dependencies.33. What happens to attributes like
classpassed 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;classandstyleare merged. UseinheritAttrs: falsewithv-bind="$attrs"to move them elsewhere.34. What does
<style scoped>do?Correct answer: Limits the styles to this component with
data-v-*The compiler rewrites
.btnto.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. How does a parent use
v-modelon 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'sv-modeldefineModeldeclares amodelValueprop and anupdate:modelValueevent under the hood. Named models are supported too:v-model:titlewithdefineModel('title').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: trueanddefaultVue 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. How do you switch between several components dynamically?
<component :is="tabs[current]" />Correct answer: With the built-in
<component :is="...">element:isaccepts an imported component or a registered component name. When switching, the old component is unmounted unless it is wrapped in<KeepAlive>.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:
providein an ancestor,injectin the descendantprovide/injectavoids prop drilling. If you provide a ref, the injected value stays reactive. For app-wide state, Pinia is usually a better fit.39. Why is
v-htmldangerous?<div v-html="comment.body"></div>Correct answer: It inserts raw HTML, so user content can run scripts
Vue escapes
{{ }}output, butv-htmlbypasses that. Only use it with trusted content or HTML sanitized by a library such as DOMPurify.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.onMountedruns after the first render; it is also never called during SSR.41. What is
onUnmountedused for?Correct answer: Cleaning up timers, listeners and subscriptions
Anything set up manually in
onMounted(setInterval,addEventListener) must be torn down inonUnmounted, or it keeps running and leaks memory.42. When should you use
watchinstead ofcomputed?Correct answer: When a change must trigger a side effect
computedreturns a derived value;watchruns code.watch(id, async (newId) => { data.value = await load(newId) })is a typical use.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 therefattribute. The value isnulluntil the element is mounted.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. How do you create a navigation link without reloading the page?
Correct answer:
<RouterLink to="/about">About</RouterLink>RouterLinkrenders an<a>with the correcthref, handles the click on the client and adds active classes (router-link-active).46. How do you read the
:idparam of the route/users/:idin<script setup>?Correct answer:
useRoute().params.iduseRoute()returns the reactive current route (params, query, hash).useRouter()returns the router instance for navigation.47. How do you navigate from code, e.g. after saving a form?
Correct answer:
const router = useRouter(); router.push('/users/' + id)router.pushadds a history entry,router.replacereplaces the current one androuter.back()goes back. Both accept strings or objects like{ name: 'user', params: { id } }.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. 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 functionsThis is a setup store; there are also option stores with
state,gettersandactions. The store is created on first use and shared across components.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. What do the
.stopand.onceevent modifiers do?<button @click.stop="select">Select</button> <button @click.once="subscribe">Subscribe</button>Correct answer:
.stopstops propagation,.oncefires only the first timeModifiers keep handlers focused on logic instead of DOM details. Others include
.prevent,.self,.captureand.passive.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.enterVue provides aliases like
.enter,.esc,.tab,.spaceand system modifiers like.ctrlor.exact.53. What does
v-model.trimdo?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. What does
v-model.lazychange?Correct answer: The value syncs on
changeinstead ofinputIt reduces updates while the user types - useful when every change triggers expensive work.
55. How do you bind several inline styles from an object?
<div :style="{ color: textColor, fontSize: size + 'px' }"></div>Correct answer: Bind
:styleto an object of properties:stylealso accepts an array of objects. Vue adds vendor prefixes when needed.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. What does
v-oncedo?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. What does
<li v-for="n in 3">{{ n }}</li>render?Correct answer: 1, 2, 3
v-forwith a number repeats the template that many times, starting from 1, unlike array indices.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 followsObject.keys().60. How do you apply
v-ifto 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-ifon an invisible<template><template>isn't rendered in the final DOM. It also works withv-forandv-else.61. Why does
v-forneed 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. 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
$eventvariableAn inline arrow function also works:
@click="(e) => remove(item.id, e)".63. How should a prop declared as
userNamebe written in a parent template?Correct answer:
user-name="...", by conventionProps are declared in camelCase in JavaScript, and kebab-case in templates matches HTML attribute conventions.
64. What value does a
Booleanprop get with<MyButton disabled />?Correct answer:
trueVue casts the presence of the attribute to
true, like native boolean attributes. Without the attribute it'sfalse.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
emitare passed to the listener. In an inline handler the first one is available as$event.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. How do you navigate to a route by its name?
router.push({ name: 'user', params: { id: 42 } })Correct answer: Pass
nameandparamstorouter.pushNamed routes don't break when the URL path changes, and params are encoded automatically.
68. Which classes does
<RouterLink>add to an active link by default?Correct answer:
router-link-active,router-link-exact-activeThe class names can be changed per link (
active-class) or globally increateRouter.69. How do you make
/open/home?{ path: '/', redirect: '/home' }Correct answer: Add a route with
redirectThe URL changes to
/home. Analiasinstead keeps the original URL while showing the same component.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 inroute.params.pathMatch.71. What is a getter in a Pinia store?
Correct answer: A cached derived value, like
computedIn setup stores getters are simply
computed()values. Put async work and mutations into actions.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. Which environment variables are exposed to client code in a Vite project?
const api = import.meta.env.VITE_API_URLCorrect answer: Only variables prefixed with
VITE_Values are embedded at build time and are public. Never put secrets into
VITE_variables.74. Which is the recommended default for reactive state in the Composition API?
Correct answer:
ref(), as it works with any value typeThe Vue docs recommend
refas the primary API becausereactiveonly works with objects and loses reactivity on destructuring or replacement.75. Why can a ref declared with
conststill change?const count = ref(0) count.value++ // worksCorrect answer:
constonly blocks reassigning the variable itselfWriting
count = ref(1)would fail and also break every place that holds the old ref. Usereadonly()to make a value truly read-only.