vue.joedoe.dev

← All the recipesComponentsVue 3.5+

Labels and ids that always match: useId

A unique id per instance, identical on server and browser. So every label points at its input without making ids up.

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.

↑↓ move · ↵ open · esc close