bhylu.com

Advertisements

Vue Exercises

Practise derived filtering without mutating the source inventory.

How it works

Start by predicting which records appear for the default query. Then change the query and verify the result. Extend the example with a minimum count while keeping the original inventory unchanged. The worked solution below uses a computed filtered view. As a separate exercise, make an empty result message that does not pretend an empty display means the underlying inventory has been deleted.

Run the code

Use a separate empty learning folder with Node 22.12+ in the 22 series. The reviewed Node version is 22.15.1. Save all files below with their exact relative paths; downloads may keep only the basename, so create src and any tests folders as listed. This project pins Vue 3.5.44 and Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints.

Bhylu has no Vue playground. SFCs, npm imports and routing need this local project; do not paste them into the plain HTML or JavaScript editor. Apache, MySQL and changes to Bhylu server settings are not required. The application is a fictional seed-swap learning fixture.

Example

src/App.vue

<script setup>
import { ref, computed } from "vue";

const query = ref("be");
const packets = ref([
  { id: "bean", name: "Beans" },
  { id: "pea", name: "Peas" },
]);
const visible = computed(() =>
  packets.value.filter((p) =>
    p.name.toLowerCase().includes(query.value.toLowerCase()),
  ),
);
</script>

<template>
  <main>
    <h1>Riverside seed swap</h1>
    <label for="query">Filter varieties</label
    ><input id="query" v-model="query" />
    <ul>
      <li v-for="packet in visible" :key="packet.id">{{ packet.name }}</li>
    </ul>
    <output data-result
      >{{ visible.length }} shown / {{ packets.length }} total</output
    >
  </main>
</template>

Expected result

The initial filter shows one of two records; clearing it shows both.

The computed filter creates a view from the array rather than overwriting the array. This preserves the records when the search is cleared. Explain why changing the source to its filtered subset would make a later reset impossible without another copy or fetch. Then add a test for an unmatched query.

Check APIs and version differences in the official Vue guide.