A smart Vue autofocus directive

The directive in this package, v-autofocus
, tries to be smart in the following ways:
Please note: in this context, an element is considered "focusable" if it can become the
document.activeElement
.
This includes contenteditable
elements.
Focusable elements become non-focusable only if hidden or having attribute disabled
.
Elements with any integer tabindex
value are at least click focusable.
Installation
As a module:
$ npm install @undecaf/vue-autofocus
or
$ yarn add @undecaf/vue-autofocus
Included as <script>
:
<script src="https://cdn.jsdelivr.net/npm/@undecaf/vue-autofocus/dist/directives.min.js"></script>
Usage
Registering the directive
import autofocus from 'vue-autofocus'
Vue.use(autofocus)
Configuration
v-autofocus
expects a configuration object, a primitive value as a single option (see below), or no
value at all. Unspecified options get default values.
The configuration object supports the following properties:
Name | Type | Effect | Default |
---|
enabled | Boolean | Enables the directive if truthy. | true |
selector | String | Only an element matching this selector can receive the focus. | '*' |
on | String or Array<String> | Child event(s) that re-trigger auto-focusing. | [] |
delay | Number | Delay (in ms) until the focus is set. A value of 0 sets the focus synchronously with the trigger event. | 50 |
If a primitive value is specified rather than an object then the type determines which option it applies to:
Boolean
→ enabled
, String
→ selector
, Array
→ on
, Number
→ delay
.
Options can be dynamic; changes to on
take effect immediately, all other changes become noticeable only after a child event
(e.g. 'hook:updated'
or
'md-opened'
).
Examples
A simple use case:
<input type="text" v-autofocus>
Conditional autofocus:
<input type="text" v-autofocus="{ enabled: active }">
Focusing on the first focusable child:
<div v-autofocus>
<div><span>Not focusable</span></div>
<img src="#">
<a></a>
<input type="hidden">
<input type="text" disabled>
<div>
<textarea v-model="comment"></textarea>
</div>
</div>
Focusing on the first focusable child that matches a selector:
<div autofocus="{ selector: '.focus-me' }">
<textarea v-model="comment"></textarea>
<input type="text" class="focus-me" v-model="text">
</div>
Auto-focusing on the input inside a Vue Material Datepicker:
<md-datepicker v-autofocus v-model="birthdate" :md-open-on-focus="false" />
Setting the focus on the first input of a Vue Material Dialog
whenever the dialog is (re-)opened (a selector is required since the dialog container is
focusable):
<md-dialog v-autofocus="{ selector: 'input', on: 'md-opened' }" :md-active="showDialog">
...
</md-dialog>
This will have no effect whatsoever:
<div v-autofocus>
<input type="hidden">
</div>
License
MIT