Tech Interview RoomStudy guides

Vue.js

Explain the core template directives: v-if vs v-show, v-for, v-bind and v-on.

Beginner · 2 min read · Lesson 2 of 12 in Vue.js

Conditional rendering

  • v-if / v-else-if / v-else: the element is created or destroyed. Its components mount and unmount. Higher toggle cost, zero cost when false.
  • v-show: the element is always rendered; only CSS display: none toggles. Higher initial cost, cheap toggling. Use for things toggled often, such as a dropdown.

Lists

v-for="item in items" :key="item.id". Always give a unique, stable key so Vue can reuse and move elements correctly. Do not put v-if and v-for on the same element: in Vue 3 v-if runs first and cannot see the loop variable; filter with a computed property, or wrap with <template v-for>.

Binding and events

  • v-bind:href="url", short form :href="url". :class and :style accept objects and arrays. v-bind="obj" spreads attributes.
  • v-on:click="handler", short form @click. Modifiers: @submit.prevent, @click.stop, @keyup.enter, .once, .self.
  • v-model gives two-way binding on inputs (and components).
  • v-html sets raw HTML: never use it with user input (XSS).

Example

vue
<script setup>
import { ref, computed } from 'vue';
const tasks = ref([
  { id: 1, title: 'Write tests', done: false },
  { id: 2, title: 'Review PR', done: true },
]);
const showDone = ref(true);
const visible = computed(() => tasks.value.filter(t => showDone.value || !t.done));
const menuOpen = ref(false);
</script>

<template>
  <label><input type="checkbox" v-model="showDone" /> Show done</label>

  <ul v-if="visible.length">
    <li v-for="task in visible" :key="task.id" :class="{ done: task.done }">
      <input type="checkbox" v-model="task.done" /> {{ task.title }}
    </li>
  </ul>
  <p v-else>Nothing to do 🎉</p>

  <button @click="menuOpen = !menuOpen">Menu</button>
  <nav v-show="menuOpen">…</nav>
</template>

Follow-up questions interviewers ask

Try answering each one before you open it.

What do the v-model modifiers do?

.lazy updates on change instead of every input event; .number casts the value with parseFloat; .trim removes surrounding whitespace. Components can define their own modifiers through defineModel.