A smart Vue autofocus directive
@undecaf/vue-autofocus" alt="Minified size">
@undecaf/vue-autofocus/badge.svg" alt="Vulnerabilities">
@undecaf/vue-autofocus" alt="Total downloads">
This directive, v-autofocus
, tries to be smart in the following ways:
<div>
) or a Vue component,contenteditable
elements, too.v-autofocus
to work with opaque Vue input components such as thev-autofocus
can act with some delay in order to be compatible with container componentsA simple online example is available here
(example source code).
Please note: in this context, an element is considered “focusable” if it can become thedocument.activeElement
.
This includes contenteditable
elements.
Focusable elements become non-focusable only if hidden or having attribute disabled
.
Elements with any integer tabindex
are at least click focusable.
As a module:
```shell script
$ npm install @undecaf/vue-autofocus
or
$ yarn add @undecaf/vue-autofocus
Included as `<script>`:
```html
<script src="https://cdn.jsdelivr.net/npm/@undecaf/vue-autofocus/dist/directives.min.js"></script>
```javascript 1.8
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 | Description | Default |
|------|------|-------------|---------|
| `enabled` | `Boolean` | Enables the directive if truthy. | `true` |
| `selector` | `String` | Only an element matching this selector can receive the focus, starting with the element on which this directive is placed. | `'*'` |
| `on` | `String` or `Array<String>` | Child event(s) that re-trigger auto-focusing. | `[]` |
| `delay` | `Number` | Delay (in ms) until the focus is set.<br>A value of `0` sets the focus synchronously with the trigger event. | `50` |
If a value is specified that is not an object then its type determines which option it applies to:
`Boolean` → `enabled`, `String` → `selector`, `Array` → `on`, `Number` → `delay`.
The configuration can be modified after binding; changes to `on` take effect immediately, all other changes become noticeable only after a child event
(e.g. [`'hook:updated'`](https://twitter.com/DamianDulisz/status/981549658571968512) or
[`'md-opened'`](https://vuematerial.io/components/dialog)).
### Examples
A simple use case:
```html
<input type="text" v-autofocus>
Conditional autofocus:
<input type="text" v-autofocus="{ enabled: active }"> <!-- or: autofocus="Boolean(active)" -->
Focusing on the first focusable descendant:
```html