@aburai/vue-autofocus

Vue plugin to help manage focus handling.

Usage no npm install needed!

<script type="module">
  import aburaiVueAutofocus from 'https://cdn.skypack.dev/@aburai/vue-autofocus';
</script>

README

vue-autofocus

UNDER CONSTRUCTION - use at own risc and create issues

Introduction

vue-autofocus is a plugin for Vue.js. Features include:

  • many supported selectors to query control to focus
  • options for finetuning (see default global options)
  • option for debugging (logs focus workflow)

Install

From npm:

$ npm install @aburai/vue-autofocus --save
$ yarn add @aburai/vue-autofocus

Usage

append plugin to Vue

import Vue from 'vue'
import VueAutofocus from '@aburai/vue-autofocus'
Vue.use(VueAutofocus)
// OR
Vue.use(VueAutofocus, {globalOptions})

default global options

{
  initDelay: 300,
  focusDelay: 100,
  refocusDelay: 100,
  select: true,
  debug: false
}

use plugin

mounted() {
    this.$autofocus() // use this.$el to find a focusable control
    this.$autofocus('#my-element') // find element by id in this.$el
    this.$autofocus(this.$refs.form)
    this.$autofocus({ref: 'form'}) // get selector from this.$refs after $nextTick
    this.$autofocus(this.$refs.dialog, {initDelay: 600, debug: true})
    this.$autofocus(this.$refs.input, {select: false}) // do not select input text
}

Troubleshooting

example: focus on dialog element in a watcher with ref

wrong

watch: {
  dialog(state) {
    // this.$refs.dialogcard could be undefined
    if (state) this.$autofocus(this.$refs.dialogcard)
  }
}

correct

watch: {
  dialog(state) {
    if (state) this.$nextTick(() => this.$autofocus(this.$refs.dialogcard))
    // OR
    if (state) this.$autofocus({ref: 'dialogcard'})
  }
}

License

MIT

Copyright (c) 2019-present André Bunse (aburai)

Special Thanks

to vue-router as a boilerplate for a good vue plugin template