JAVASCRIPT
Programmatic Focus Control for Improved Accessibility in Vue 3
Learn to programmatically set focus on elements in Vue 3 using template refs and `nextTick` for enhanced accessibility, especially after conditional rendering or state changes.
<template>
<div>
<button @click="showInput = !showInput">Toggle Input</button>
<div v-if="showInput">
<label for="my-input">Enter text:</label>
<input type="text" id="my-input" ref="myInputRef" @keyup.enter="handleEnter">
</div>
</div>
</template>
<script setup>
import { ref, nextTick, watch } from 'vue';
const showInput = ref(false);
const myInputRef = ref(null); // Create a ref to link to the input element
// Watch for changes in showInput and focus the input when it becomes visible
watch(showInput, (newVal) => {
if (newVal) {
nextTick(() => {
myInputRef.value?.focus(); // Safely focus the input element
});
}
});
const handleEnter = () => {
alert('Enter pressed in input!');
// You could also move focus to another element here if needed
};
</script>
How it works: Programmatically controlling focus is crucial for web accessibility, guiding users (especially those relying on keyboard navigation or screen readers) through interactive elements. In Vue 3, you can achieve this by creating a `ref` and attaching it to your desired DOM element in the template (`ref="myInputRef"`). Then, use `myInputRef.value.focus()` within a `nextTick` callback to ensure the DOM has been updated before attempting to focus, particularly after conditional rendering or state changes where the element might not exist yet.