From 9b4fa35848ebba2a99cab46dc5ac9a6363ed67c4 Mon Sep 17 00:00:00 2001 From: sifu <2587107273@qq.com> Date: Tue, 15 Aug 2023 16:01:00 +0800 Subject: [PATCH] fix:cannot read property 'contains' of undefined --- src/vue-bottom-sheet-vue2.vue | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/vue-bottom-sheet-vue2.vue b/src/vue-bottom-sheet-vue2.vue index 4b422b8..ef41ebd 100644 --- a/src/vue-bottom-sheet-vue2.vue +++ b/src/vue-bottom-sheet-vue2.vue @@ -217,21 +217,25 @@ export default { document.documentElement.style.overscrollBehavior = 'none' this.showSheet = true this.$emit('opened') - } + }, + keyupHandler(event){ + const isFocused = (element) => document.activeElement === element + const isSheetElementFocused = + this.$refs.bottomSheet.contains(event.target) && isFocused(event.target) + + if (event.key === 'Escape' && !isSheetElementFocused) { + this.close() + } + }, + }, + beforeDestroy() { + window.removeEventListener('keyup', this.keyupHandler) }, async mounted() { setTimeout(() =>{ this.initHeight() - const isFocused = (element) => document.activeElement === element - window.addEventListener('keyup', (event) => { - const isSheetElementFocused = - this.$refs.bottomSheet.contains(event.target) && isFocused(event.target) - - if (event.key === 'Escape' && !isSheetElementFocused) { - this.close() - } - }) + window.addEventListener('keyup', this.keyupHandler) /** * Create instances of Hammerjs