Vue component to trap the focus within a DOM element
npm install focus-trap-vue> Vue component to trap the focus within a DOM element
``sh`
npm install focus-trap focus-trap-vue@legacy
`sh`
npm install focus-trap focus-trap-vue
This library exports one single named export FocusTrap and **requiresfocus-trap as a peer
dependency**. So you can locally import the component or declare it globally:
`js
import { FocusTrap } from 'focus-trap-vue'
Vue.component('FocusTrap', FocusTrap)
`
`js
import { FocusTrap } from 'focus-trap-vue'
createApp(App)
.component('FocusTrap', FocusTrap)
.mount('#app')
`
Note this documentation is for Vue 3 and some props/events might not exist in the Vue 2 version
FocusTrap can be controlled in three different ways:
- by using the active _Boolean_ propv-model:active
- by using (uses the active prop, _Vue 3 only_)activate
- by calling the /deactivate method on the component
The recommended approach is using v-model:active and it should contain one single child:
` Do you accept the cookies?html`
When isActive becomes true, it activates the focus trap. By default it setstabindex="-1"
the focus to its child, so make sure the element is a focusable element. If it's
not you wil need to give it the attribute. You can also
customize the initial element focused. This element should be an element that
the user can interact with. For example, an input. It's a good practice to
always focus an interactable element instead of the modal container:
` What name do you want to use?html`
FocusTrap also accepts other props:
- escapeDeactivates: booleanreturnFocusOnDeactivate
- : booleanallowOutsideClick
- : boolean | ((e: MouseEvent | TouchEvent) => boolean)clickOutsideDeactivates
- : boolean | ((e: MouseEvent | TouchEvent) => boolean)initialFocus
- : string | (() => Element) _Selector or function returning an Element_fallbackFocus
- : string | (() => Element) _Selector or function returning an Element_delayInitialFocus
- : booleantabbableOptions
- : FocusTrapTabbableOptions _Options passed to tabbableOptions_
Please, refer to
focus-trap
documentation to know what they do.
FocusTrap emits 2 events. They are in-sync with the prop active
- activate: Whenever the trap activatesdeactivate
- : Whenever the trap deactivates (note it can also be deactivated by
pressing Esc or clicking outside)
FocusTrap can be used without v-model:active. In that case, you will use the
methods and _probably_ need to initialize the trap as _deactivated_, otherwise,
the focus will start as active:
`html
Hello there!
`
Note the use of arrow functions, this is necessary because we are accessing
$refs` which are unset on first render.
- Focus Trap: https://github.com/focus-trap/focus-trap