Composition API oppure Options API?
Approfondimento: React Hooks: useState, useEffect and More (EN).
Entrambe usano il sistema reattivo di Vue. Options API raggruppa il codice per tipo di opzione, Composition API per funzionalità. Non serve migrare componenti funzionanti solo per stile. Nei SFC, <script setup> viene compilato in logica setup per ogni istanza, non rieseguita a ogni render come il corpo di un componente funzionale React. [1][2]
ref, reactive e computed
reactivity.ts
import { computed, reactive, ref, toRefs } from "vue";
export function useQuantity() {
const quantity = ref(1);
const pricing = reactive({ unitPrice: 2500 });
const { unitPrice } = toRefs(pricing);
const total = computed(() => quantity.value * unitPrice.value);
return { quantity, unitPrice, total };
}
ref espone .value in TypeScript; il template estrae automaticamente le ref di primo livello. reactive crea un proxy. Destrutturare una proprietà numerica o testuale ordinaria interrompe il tracciamento; toRefs mantiene il collegamento. computed memorizza il calcolo secondo le dipendenze reattive. Nel getter non avviare richieste né mutare lo stato. Il prezzo usa unità monetarie minori, non un modello finanziario completo. [3][4]
watch, watchEffect e pianificazione
watch dichiara la fonte e attende cambiamenti per impostazione predefinita; immediate attiva il primo callback. watchEffect parte subito e traccia letture sincrone, non quelle dopo il primo await. I watcher predefiniti sono raggruppati ed eseguiti prima dell’aggiornamento DOM del componente. flush: "post" permette di leggere il DOM aggiornato. nextTick() attende la coda di Vue, non necessariamente il disegno. flush: "sync" evita il raggruppamento; qui solo per un testo, così da invalidare subito le vecchie ricerche. [3][5]
Contratto HTTP e validazione a runtime
Approfondimento: TypeScript Type Guards: Narrowing and Runtime Validation (EN).
products.ts
export interface Product {
readonly id: string;
readonly name: string;
}
function isRecord(value: unknown): value is Record<string, unknown> {
if (value === null) {
return false;
}
if (Array.isArray(value)) {
return false;
}
return typeof value === "object";
}
function isNonBlankString(value: unknown): value is string {
if (typeof value !== "string") {
return false;
}
return value.trim().length > 0;
}
export function parseProducts(value: unknown): readonly Product[] {
if (!Array.isArray(value)) {
throw new TypeError("Expected a product array.");
}
const entries: unknown[] = value;
const ids = new Set<string>();
const products: Product[] = [];
for (const item of entries) {
if (!isRecord(item)) {
throw new TypeError("Expected a product object.");
}
const { id, name } = item;
if (!isNonBlankString(id)) {
throw new TypeError("Invalid product ID.");
}
if (!isNonBlankString(name)) {
throw new TypeError("Invalid product name.");
}
if (ids.has(id)) {
throw new TypeError("Duplicate product ID.");
}
ids.add(id);
products.push({ id, name });
}
return products;
}
products-api.ts
import { parseProducts } from "./products";
import type { Product } from "./products";
export type ProductLoader = (
query: string,
signal: AbortSignal,
) => Promise<readonly Product[]>;
const REQUEST_TIMEOUT_MS = 10_000;
export function createProductLoader(
endpoint: URL,
transport: typeof fetch = fetch,
): ProductLoader {
return async (query, signal) => {
const url = new URL(endpoint);
url.searchParams.set("q", query);
const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
const requestSignal = AbortSignal.any([signal, timeout]);
const response = await transport(url, {
signal: requestSignal,
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data: unknown = await response.json();
return parseProducts(data);
};
}
Un generico TypeScript non valida le risposte del server. L’adattatore riceve URL e trasporto, codifica la ricerca con URLSearchParams, combina annullamento e scadenza e verifica lo stato HTTP prima del JSON. Il parser rifiuta record non validi, nomi vuoti e ID duplicati, usati come chiavi. Le guard clauses separano struttura e valore. Il backend deve applicare autonomamente autorizzazioni e limiti di richiesta. [6][7] [13][16]
Composable: stato e annullamento
use-product-search.ts
import { computed, ref, shallowRef, watch } from "vue";
import type { ProductLoader } from "./products-api";
import type { Product } from "./products";
type SearchState =
| { readonly status: "idle" }
| { readonly status: "loading" }
| { readonly status: "success"; readonly items: readonly Product[] }
| { readonly status: "error" };
export const SEARCH_DELAY_MS = 300;
export function useProductSearch(load: ProductLoader) {
const query = ref("");
const normalizedQuery = computed(() => query.value.trim());
const state = shallowRef<SearchState>({ status: "idle" });
watch(
normalizedQuery,
(term, _previousTerm, onCleanup) => {
if (term.length === 0) {
state.value = { status: "idle" };
return;
}
const controller = new AbortController();
async function execute(): Promise<void> {
try {
const items = await load(term, controller.signal);
if (controller.signal.aborted) {
return;
}
state.value = { status: "success", items };
} catch {
if (controller.signal.aborted) {
return;
}
state.value = { status: "error" };
}
}
const timer = setTimeout(() => {
void execute();
}, SEARCH_DELAY_MS);
onCleanup(() => {
clearTimeout(timer);
controller.abort();
});
state.value = { status: "loading" };
},
{ flush: "sync" },
);
return { query, state: computed(() => state.value) };
}
useProductSearch riceve una funzione di caricamento e restituisce una ref di ricerca e una ref calcolata in sola lettura. L’unione discriminata separa successo ed errore. Ogni modifica del testo normalizzato elimina il timer precedente e annulla la richiesta tramite cleanup del watcher. Controllare il segnale dopo await protegge anche da fonti che ignorano l’annullamento. shallowRef è adatto alla sostituzione integrale dello stato. I 300 ms sono una scelta UX esemplificativa. [5][8][9]
Componente, props e ciclo di vita
ProductSearch.vue
<script setup lang="ts">
import { useId } from "vue";
import type { ProductLoader } from "./products-api";
import { useProductSearch } from "./use-product-search";
const props = defineProps<{ load: ProductLoader }>();
const searchId = useId();
const { query, state } = useProductSearch((term, signal) =>
props.load(term, signal),
);
</script>
<template>
<section class="product-search">
<label :for="searchId">Search products</label>
<input :id="searchId" v-model="query" type="search" />
<p role="status">
<template v-if="state.status === 'loading'">Searching…</template>
<template v-else-if="state.status === 'success'">
{{ state.items.length }} results
</template>
<template v-else-if="state.status === 'error'">
Search failed. Change the query to try again.
</template>
</p>
<ul v-if="state.status === 'success'">
<li v-for="item in state.items" :key="item.id">
{{ item.name }}
</li>
</ul>
</section>
</template>
<style scoped src="./product-search.css"></style>
product-search.css
.product-search {
display: grid;
gap: 0.75rem;
max-inline-size: 36rem;
}
.product-search input {
font: inherit;
padding: 0.625rem;
}
Il SFC usa v-model, un’etichetta associata con useId e un messaggio di stato. Le direttive Vue sono collegamenti dichiarativi compilati, non attributi onclick nativi. Da Vue 3.5 il compilatore mantiene reattive le props destrutturate nello stesso <script setup>; passare getter o ref alle funzioni esterne anziché valori istantanei. I watcher creati sincronicamente in setup si fermano allo smontaggio. onWatcherCleanup richiede chiamata sincrona; qui l’argomento onCleanup viene registrato prima della richiesta. [2][5][10] [14][16]
SSR, stato condiviso e prestazioni
App.vue
<script setup lang="ts">
import ProductSearch from "./ProductSearch.vue";
import { createProductLoader } from "./products-api";
const endpoint = new URL("/api/products", window.location.origin);
const load = createProductLoader(endpoint);
</script>
<template>
<main>
<h1>Product catalog</h1>
<ProductSearch :load="load" />
</main>
</template>
Mantieni locale lo stato del componente, condividi la logica con composables e adotta uno store quando serve lo stesso stato in più viste. In SSR isola lo stato per richiesta, senza dati utente in singleton di modulo. Accedi a window e document solo sul client, ad esempio dopo onMounted. App.vue è solo CSR; con Nuxt o altro SSR inietta un trasporto adatto e usa il meccanismo di caricamento dell’ambiente. Misura i costi dei watcher profondi su grandi strutture. [8][9][11] [15]
Test e criteri di accettazione
use-product-search.test.ts
import { effectScope } from "vue";
import { afterEach, expect, it, vi } from "vitest";
import type { Product } from "./products";
import { SEARCH_DELAY_MS, useProductSearch } from "./use-product-search";
afterEach(() => {
vi.useRealTimers();
});
it("ignores outdated responses from non-cooperative loaders", async () => {
// Given
vi.useFakeTimers();
const scope = effectScope();
const oldItems: readonly Product[] = [{ id: "1", name: "Old" }];
const newItems: readonly Product[] = [{ id: "2", name: "New" }];
let finishOld: (items: readonly Product[]) => void = () => {};
const oldResponse = new Promise<readonly Product[]>((resolve) => {
finishOld = resolve;
});
const search = scope.run(() =>
useProductSearch(async (query) => {
if (query === "old") {
return oldResponse;
}
return newItems;
}),
);
try {
if (!search) {
throw new Error("Missing active scope.");
}
// When
search.query.value = "old";
await vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS);
search.query.value = "new";
await vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS);
finishOld(oldItems);
await vi.advanceTimersByTimeAsync(0);
// Then
expect(search.state.value).toEqual({
status: "success",
items: newItems,
});
} finally {
scope.stop();
}
});
it("cancels scheduled work when its scope stops", async () => {
// Given
vi.useFakeTimers();
const scope = effectScope();
const load = vi.fn(async () => []);
const search = scope.run(() => useProductSearch(load));
try {
if (!search) {
throw new Error("Missing active scope.");
}
// When
search.query.value = "book";
scope.stop();
await vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS);
// Then
expect(load).not.toHaveBeenCalled();
} finally {
scope.stop();
}
});
Testa parser e adattatore senza Vue. Per il composable usa effectScope, timer controllati e una fonte iniettata. Given-When-Then descrive contesto, azione e risultato senza richiedere Cucumber. Copri query vuota, errori server, JSON non valido, modifiche rapide, risposte fuori ordine e smontaggio. Verifica separatamente componente reale, focus e annunci accessibili. Il pacchetto include due test Vitest e controlli Node indipendenti, non sostitutivi di E2E. [12]
