Custom Vue focus trap directive with examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import focusTrap from './directives/focusTrap' | |
const app = createApp({ | |
// Any options here | |
}) | |
app.directive('trap', focusTrap) | |
app.mount('#app') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div | |
v-if="name === openedModal" | |
v-trap="modalIsOpen" | |
> | |
<div | |
role="dialog" | |
aria-labelledby="modalTitle" | |
> | |
<button | |
type="button" | |
aria-label="Close Modal" | |
@click="handleCloseModal" | |
@keydown.enter.prevent="handleCloseModal" | |
> | |
<!-- SVG for a close icon here --> | |
</button> | |
<div id="modalTitle"> | |
<slot name="header" /> | |
</div> | |
<div> | |
<slot name="content" /> | |
</div> | |
</div> | |
</div> | |
</template> | |
<script setup> | |
import { computed } from 'vue' | |
import { storeToRefs } from 'pinia' | |
import { useModalStore } from '../store/modules/modal' | |
defineProps({ | |
name: { | |
type: String, | |
required: true, | |
} | |
}) | |
const { openedModal } = storeToRefs(useModalStore()) | |
const modalIsOpen = computed(() => !!openedModal.value) | |
const handleCloseModal = () => { | |
// Logic for resetting "openedModal" to an empty string in the store | |
} | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createFocusTrap } from 'focus-trap' | |
let trap | |
const createTrap = (element) => { | |
trap = createFocusTrap(element, { | |
escapeDeactivates: true, | |
allowOutsideClick: true, | |
}) | |
} | |
const focusTrap = { | |
updated(element, binding) { | |
if (!trap && binding.value) { | |
const focusTrapElement = binding.arg | |
? [element, ...binding.arg] | |
: element | |
createTrap(focusTrapElement) | |
setTimeout(() => { | |
trap.activate() | |
}) | |
} else if (trap && !binding.value) { | |
trap.deactivate() | |
} | |
}, | |
} | |
export default focusTrap |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment