Config
useUniqueId
Composable per generare ID univoci per attributi ARIA e associazioni label-input nei componenti.
Firma TypeScript
export function useUniqueId(
basePrefix?: string,
options?: UseUniqueIdOptions
): {
id: Ref<string>;
regenerateId: () => string;
isIdInUse: (testId: string) => boolean;
generateUniqueId: () => string;
}
interface UseUniqueIdOptions {
prefix?: string;
suffix?: string;
length?: number; // default: 6
}
Parametri
| Parametro | Tipo | Descrizione |
|---|---|---|
basePrefix | string (opzionale) | Prefisso base dell'ID (es. 'inputtext') |
options.prefix | string (opzionale) | Prefisso aggiuntivo |
options.suffix | string (opzionale) | Suffisso aggiuntivo |
options.length | number (opzionale, default: 6) | Lunghezza della parte random |
Valore di Ritorno
| Proprietà | Tipo | Descrizione |
|---|---|---|
id | Ref<string> | ID generato, reattivo |
regenerateId | () => string | Rigenera l'ID e lo aggiorna nel ref |
isIdInUse | (testId: string) => boolean | Controlla se un ID e gia in uso nel DOM |
generateUniqueId | () => string | Genera un ID garantito univoco nel DOM corrente |
Esempio
import { useUniqueId } from '@pzeta/vue-components'
// Uso base per associare label a input
const { id } = useUniqueId('inputtext')
// id.value => 'inputtext-x7k2a1-1'
// Con prefisso e suffisso personalizzati
const { id: fieldId } = useUniqueId('field', {
suffix: 'label',
length: 8
})
// Verifica unicita nel DOM
const { generateUniqueId } = useUniqueId('modal')
const safeId = generateUniqueId()
<template>
<label :for="id">Nome</label>
<input :id="id" type="text" />
</template>
Prerequisiti
Nessun prerequisito. Non richiede ConfigPlugin o altri provider.
Note
- L'ID viene generato immediatamente (non in
onMounted), garantendo disponibilita nel primo render SSR-safe. - Un contatore statico globale garantisce l'unicita anche tra istanze multiple dello stesso componente.
- Il formato dell'ID generato e:
[basePrefix]-[prefix]-[randomPart]-[counter]-[suffix], con le parti vuote omesse. generateUniqueIdcontrolla l'esistenza nel DOM condocument.getElementById— usare solo lato client.