Close Modal on click and onKeyDown Vue3

February 22nd, 2023

close modal on click

@click on overlay div (outside of modal card), you emit the event 'closeModal'

1<!-- ModalView.vue -->
2<template>
3 <div class="modal">
4 <div class="overlay" @click="emit('closeModal')"></div>
5 <div class="modal-card">
6 <slot />
7 </div>
8 </div>
9</template>

then you listen for emitted event: @closeModal, when this event is triggered, it executes function that sets openedEmail to null.

1<ModalView v-if="openedEmail" @closeModal="openedEmail = null">
2 <MailView :email="openedEmail" />
3</ModalView>

close Modal on keyDown

1 
2<script setup>
3import { onBeforeUnmount, onMounted } from 'vue'
4const emit = defineEmits(['close'])
5 
6let onKeyDown = (event) => {
7 // console.log('keydown', event.key)
8 if(event.key === 'Escape'){
9 emit('close')
10 }
11}
12 
13onMounted(() => window.addEventListener("keydown", onKeyDown))
14onBeforeUnmount(() => window.removeEventListener("keydown", onKeyDown))
15 
16</script>

use keyDown composable

1import { useKeyDown } from '../../compositions/useKeyDown'
2 
3useKeyDown(() => { emit('closeModal')})

/composables/useKeyDown.js

1import { onMounted, onBeforeUnmount } from 'vue'
2 
3export const useKeyDown = function(fn) {
4 let onKeyDown = function(event) {
5 if(event.key == 'Escape') {
6 fn()
7 }
8 }
9 
10 onMounted(() => window.addEventListener("keydown", onKeyDown))
11 onBeforeUnmount(() => window.removeEventListener("keydown", onKeyDown))
12 
13}
14 
15export default useKeyDown

useKeyDown composable for multiple keys

ModalView.vue

1<script setup>
2import { useKeyDown } from '../../compositions/useKeyDown'
3const emit = defineEmits(['closeModal'])
4 
5useKeyDown([
6 { key: 'Escape', fn: () => { emit('closeModal') } },
7 { key: 'Enter', fn: () => { console.log('pressed Enter') } }
8])
9 
10</script>
1import { onMounted, onBeforeUnmount } from 'vue'
2 
3export const useKeyDown = function(keyCombos) {
4 let onKeyDown = function(event) {
5 // console.log(keyCombos) // array, find value == event.key
6 let kc = keyCombos.find((kc) => kc.key == event.key)
7 // console.log(kc)
8 if(kc) {
9 kc.fn()
10 }
11 }
12 
13 onMounted(() => window.addEventListener("keydown", onKeyDown))
14 onBeforeUnmount(() => window.removeEventListener("keydown", onKeyDown))
15 
16}

Related Posts