JAVASCRIPT
Vue 3 useFocus Composable for DOM Focus
Create a reusable Vue 3 composable to programmatically manage focus on elements, enhancing accessibility and user experience in forms and interactive UIs.
import { ref, watch, nextTick } from 'vue';
function useFocus() {
const elementToFocus = ref(null); // Ref to link to the DOM element
/**
* Sets focus to the specified element when it becomes available.
* @param {HTMLElement | null} element The DOM element to focus.
*/
const setFocus = (element) => {
if (element && typeof element.focus === 'function') {
element.focus();
}
};
// Watch for changes to elementToFocus and apply focus
watch(elementToFocus, (newElement) => {
if (newElement) {
// Ensure the element is mounted in the DOM before trying to focus
nextTick(() => {
setFocus(newElement);
});
}
});
return { elementToFocus, setFocus };
}
// Example Usage in a component:
// <template>
// <div>
// <button @click="focusInput">Focus Input</button>
// <input ref="inputRef" type="text" placeholder="I can be focused" />
// <button @click="focusButton">Focus Another Button</button>
// <button ref="anotherButtonRef" type="button">Another Button</button>
// </div>
// </template>
//
// <script setup>
// import { ref } from 'vue';
// import useFocus from './composables/useFocus';
//
// const { elementToFocus, setFocus } = useFocus();
//
// // Template refs for direct element binding
// const inputRef = ref(null);
// const anotherButtonRef = ref(null);
//
// const focusInput = () => {
// elementToFocus.value = inputRef.value; // Assign the template ref
// };
//
// const focusButton = () => {
// setFocus(anotherButtonRef.value); // Use the utility function
// };
// </script>
export default useFocus;
How it works: The `useFocus` composable simplifies programmatic DOM focus management in Vue 3. It returns an `elementToFocus` ref, which can be linked to a template element via `ref="elementToFocus"`, and a `setFocus` utility function. The `watch` effect monitors `elementToFocus` and uses `nextTick` to ensure the target element is mounted in the DOM before attempting to call its `focus()` method. This is invaluable for improving accessibility, guiding user interaction in forms, or implementing keyboard navigation in complex interfaces.