The `vue-autofocus-directive` package provides a straightforward custom directive for Vue.js applications, designed to automatically apply focus to elements upon page load or when components are rendered. Based directly on the Vue 2 custom directive tutorial, this package is explicitly compatible with Vue 2.x environments. Its current stable version is 1.0.4, with no recent updates, indicating a mature yet static codebase. The package's primary differentiator is its minimalist approach, offering a direct implementation of the autofocus pattern without introducing complex abstractions. While effective for existing Vue 2 projects, it lacks official support for Vue 3, necessitating alternative strategies or manual adaptation for newer Vue applications. Developers should be aware of browser-specific limitations, particularly regarding mobile Safari's handling of the autofocus attribute.
npm install vue-autofocus-directiveVerified import paths — ran on the pinned version, not inferred.
This code sets up a minimal Vue 2 application, registers the `v-autofocus` directive globally, and demonstrates its usage on an input field, including conditional application.
For Vue 3, consider using a custom directive registered via `app.directive('autofocus', { mounted(el) { el.focus(); } })` or a ref with `el.value.focus()` in `onMounted`.Provide clear labels and consider alternative UI patterns or a prompt for users to manually focus elements on mobile devices.
Always bind a reactive boolean value (e.g., `v-autofocus="shouldFocus"`) when conditional autofocus is desired, and update `shouldFocus` in your component's data or methods.
Ensure `import Vue from 'vue';` is present and that you are using Vue 2.x in your project. Verify Vue is globally available or imported correctly before `Vue.directive` is called.
This is a browser limitation, not a bug in the directive. Consider providing a clear visual cue for the user to tap the input, or rethink the UI flow to not rely on automatic focus on mobile devices.