Vue Exercises
Time to practise! Each task has a starter playground with a TODO. Edit the code, press ▶ Run (or Ctrl+Enter), and only open the solution after a real attempt. There is usually more than one correct answer — if yours works and reads clearly, it counts.
| # | Topic |
|---|---|
| 1 | Interpolation and v-bind |
| 2 | Events and methods |
| 3 | v-if / v-else |
| 4 | v-for with keys |
| 5 | v-model and computed |
| 6 | Class binding |
| 7 | Props and emits |
| 8 | Watchers |
| 9 | Slots |
| 10 | Composables |
Exercise 1 — Interpolation and v-bind
Show the book's title in the <h2>, and bind the image's src and alt to cover and title.
<div id="app">
<h2><!-- TODO: title --></h2>
<img width="80" src="" alt="">
</div>
<script type="module">
import { createApp } from 'vue';
createApp({
data: () => ({
title: 'Learning Vue',
cover: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 60 80'%3E%3Crect width='60' height='80' fill='%2342b883'/%3E%3C/svg%3E"
})
}).mount('#app');
</script>Show solution
<div id="app">
<h2>{{ title }}</h2>
<img width="80" :src="cover" :alt="title">
</div>Exercise 2 — Events and methods
Make the Roll button call a method roll() that cycles face through 1 → 2 → … → 6 → 1 (no random numbers), and count the rolls in rolls.
<div id="app">
<p style="font-size: 40px">🎲 {{ face }}</p>
<button>Roll</button> <!-- TODO: listen for click -->
<p>Rolls: {{ rolls }}</p>
</div>
<script type="module">
import { createApp } from 'vue';
createApp({
data: () => ({ face: 1, rolls: 0 }),
methods: {
// TODO: roll()
}
}).mount('#app');
</script>Show solution
<button @click="roll">Roll</button>
<script type="module">
// ...
methods: {
roll() {
this.face = this.face % 6 + 1;
this.rolls++;
}
}
</script>Exercise 3 — v-if / v-else
Show "✅ Strong password" when password has at least 8 characters, "⚠️ Too short" when it has 1–7, and nothing when it's empty.
<div id="app">
<input v-model="password" type="password" placeholder="Password">
<!-- TODO: messages -->
</div>
<script type="module">
import { createApp } from 'vue';
createApp({ data: () => ({ password: '' }) }).mount('#app');
</script>Show solution
<div id="app">
<input v-model="password" type="password" placeholder="Password">
<p v-if="password.length >= 8">✅ Strong password</p>
<p v-else-if="password.length > 0">⚠️ Too short</p>
</div>Exercise 4 — v-for with keys
Render each planet as an <li> showing its name and its number of moons. Use id as the key. Below the list, show the total number of moons.
<div id="app">
<ul>
<!-- TODO -->
</ul>
</div>
<script type="module">
import { createApp } from 'vue';
createApp({
data: () => ({
planets: [
{ id: 3, name: 'Earth', moons: 1 },
{ id: 4, name: 'Mars', moons: 2 },
{ id: 6, name: 'Saturn', moons: 146 }
]
})
}).mount('#app');
</script>Show solution
<ul>
<li v-for="p in planets" :key="p.id">{{ p.name }} — {{ p.moons }} moon(s)</li>
</ul>
<p>Total moons: {{ planets.reduce((sum, p) => sum + p.moons, 0) }}</p>A computed property totalMoons would be even cleaner than the inline reduce.
Exercise 5 — v-model and computed
Build a tip calculator: bind the two inputs with v-model.number, then add computed properties tip and perPerson (bill + tip divided by people), shown with 2 decimals.
<div id="app">
<p>Bill: <input type="number"> €</p>
<p>Tip %: <input type="number"></p>
<p>People: <input type="number" v-model.number="people" min="1"></p>
<p>Tip: ? € — each pays ? €</p> <!-- TODO: show tip and perPerson -->
</div>
<script type="module">
import { createApp } from 'vue';
createApp({
data: () => ({ bill: 60, percent: 10, people: 3 }),
computed: {
// TODO
}
}).mount('#app');
</script>Show solution
<div id="app">
<p>Bill: <input type="number" v-model.number="bill"> €</p>
<p>Tip %: <input type="number" v-model.number="percent"></p>
<p>People: <input type="number" v-model.number="people" min="1"></p>
<p>Tip: {{ tip.toFixed(2) }} € — each pays {{ perPerson.toFixed(2) }} €</p>
</div>
<script type="module">
import { createApp } from 'vue';
createApp({
data: () => ({ bill: 60, percent: 10, people: 3 }),
computed: {
tip() { return this.bill * this.percent / 100; },
perPerson() { return (this.bill + this.tip) / Math.max(1, this.people); }
}
}).mount('#app');
</script>Exercise 6 — Class binding
Clicking a seat should toggle it in the selected array. Give selected seats the class chosen and taken seats the class taken (taken seats can't be clicked).
<style>
.seat { display: inline-block; width: 34px; margin: 3px; padding: 6px 0; text-align: center; background: #e5e7eb; cursor: pointer; }
.chosen { background: #42b883; color: white; }
.taken { background: #9ca3af; cursor: not-allowed; }
</style>
<div id="app">
<span v-for="n in 10" :key="n" class="seat">{{ n }}</span> <!-- TODO -->
<p>Selected: {{ selected.join(', ') || 'none' }}</p>
</div>
<script type="module">
import { createApp } from 'vue';
createApp({
data: () => ({ taken: [2, 3, 7], selected: [] }),
methods: {
toggle(n) {
// TODO
}
}
}).mount('#app');
</script>Show solution
<span v-for="n in 10" :key="n" class="seat"
:class="{ chosen: selected.includes(n), taken: taken.includes(n) }"
@click="toggle(n)">{{ n }}</span>
<script type="module">
// ...
methods: {
toggle(n) {
if (this.taken.includes(n)) return;
const i = this.selected.indexOf(n);
i === -1 ? this.selected.push(n) : this.selected.splice(i, 1);
}
}
</script>Exercise 7 — Props and emits
Finish the color-swatch component: it receives a color prop, shows a coloured square, and emits pick with its colour when clicked. The parent already listens with @pick.
<div id="app">
<color-swatch v-for="c in colors" :key="c" :color="c" @pick="picked = $event"></color-swatch>
<p :style="{ color: picked }">Picked: {{ picked || 'nothing yet' }}</p>
</div>
<script type="module">
import { createApp } from 'vue';
const app = createApp({ data: () => ({ colors: ['#ef4444', '#f59e0b', '#42b883', '#3b82f6'], picked: '' }) });
app.component('color-swatch', {
// TODO: props, emits
template: `<span style="display:inline-block;width:40px;height:40px;margin:4px;cursor:pointer"></span>`
});
app.mount('#app');
</script>Show solution
app.component('color-swatch', {
props: { color: { type: String, required: true } },
emits: ['pick'],
template: `<span style="display:inline-block;width:40px;height:40px;margin:4px;cursor:pointer"
:style="{ background: color }" @click="$emit('pick', color)"></span>`
});A static style and a bound :style on the same element are merged, just like class.
Exercise 8 — Watchers
When count reaches a multiple of 5, push a message such as "Milestone: 5" into log. Use a watcher, not the click handler.
<div id="app">
<button @click="count++">Count: {{ count }}</button>
<ul><li v-for="(m, i) in log" :key="i">{{ m }}</li></ul>
</div>
<script type="module">
import { createApp, ref, watch } from 'vue';
createApp({
setup() {
const count = ref(0);
const log = ref([]);
// TODO: watch(count, ...)
return { count, log };
}
}).mount('#app');
</script>Show solution
watch(count, (value) => {
if (value % 5 === 0) log.value.push(`Milestone: ${value}`);
});Exercise 9 — Slots
Give info-panel a named slot title (fallback text "Info") and a default slot for the body, then use both from the parent.
<style> .panel { border: 2px solid #42b883; border-radius: 8px; max-width: 280px; } .panel h4 { margin: 0; background: #42b883; color: white; padding: 6px 10px; } .panel div { padding: 10px; } </style>
<div id="app">
<info-panel>
<!-- TODO: fill the title and body -->
</info-panel>
</div>
<script type="module">
import { createApp } from 'vue';
const app = createApp({});
app.component('info-panel', {
template: `<section class="panel"><h4>TODO title</h4><div>TODO body</div></section>`
});
app.mount('#app');
</script>Show solution
<info-panel>
<template #title>Opening hours</template>
Mon–Fri 9:00–17:00
</info-panel>
<script type="module">
// ...
app.component('info-panel', {
template: `
<section class="panel">
<h4><slot name="title">Info</slot></h4>
<div><slot></slot></div>
</section>`
});
</script>Exercise 10 — A composable
Write a composable useToggle(initial) that returns { on, toggle }, and use it twice so the two switches are independent.
<div id="app">
<p>Wi-Fi: {{ wifi ? 'on' : 'off' }} <button>toggle</button></p>
<p>Bluetooth: {{ bluetooth ? 'on' : 'off' }} <button>toggle</button></p>
</div>
<script type="module">
import { createApp, ref } from 'vue';
// TODO: function useToggle(initial = false) { ... }
createApp({
setup() {
const wifi = ref(true); // TODO: use useToggle instead
const bluetooth = ref(false);
return { wifi, bluetooth };
}
}).mount('#app');
</script>Show solution
<div id="app">
<p>Wi-Fi: {{ wifi ? 'on' : 'off' }} <button @click="toggleWifi">toggle</button></p>
<p>Bluetooth: {{ bluetooth ? 'on' : 'off' }} <button @click="toggleBluetooth">toggle</button></p>
</div>
<script type="module">
import { createApp, ref } from 'vue';
function useToggle(initial = false) {
const on = ref(initial);
const toggle = () => { on.value = !on.value; };
return { on, toggle };
}
createApp({
setup() {
const { on: wifi, toggle: toggleWifi } = useToggle(true);
const { on: bluetooth, toggle: toggleBluetooth } = useToggle(false);
return { wifi, toggleWifi, bluetooth, toggleBluetooth };
}
}).mount('#app');
</script>Test yourself
Which directive would you use to show a list of items from an array?
v-ifv-forv-showv-model
A component should tell its parent that the user chose a colour. What does it use?
- A prop
$emitv-html- A template ref
Which is the best tool to derive perPerson from bill, tip and people?
- A watcher
- A computed property
- A lifecycle hook
v-once