vue.joedoe.dev

← Totes les receptesComponentsVue 3.5+

Etiquetes i ids que sempre casen: useId

Un id únic per instància i igual al servidor i al navegador. Perquè cada label apunti al seu input sense inventar-se ids.

Vue SFC
<script setup lang="ts">
import { useId } from "vue";

/*
 * Vue 3.5: useId gives an id that is unique per instance and the same on the
 * server and in the browser, so label, input and hint always match.
 */
const value = defineModel<string>({ default: "" });
const { label, hint } = defineProps<{ label: string; hint?: string }>();
const id = useId();
</script>

<template>
	<div class="field">
		<label :for="id">{{ label }}</label>
		<input :id="id" v-model="value" :aria-describedby="hint ? `${id}-hint` : undefined" />
		<small v-if="hint" :id="`${id}-hint`">{{ hint }}</small>
	</div>
</template>

<style scoped>
.field {
	display: grid;
	gap: 0.2rem;
	margin-bottom: 0.75rem;
}
small {
	opacity: 0.7;
}
</style>
Como quieras que te llamemos

Haz clic en una etiqueta: el foco va a su campo.

↑↓ moure's · ↵ obrir · esc tancar