【问题标题】:How do I handle the "keydown.esc" event in Vue3?如何处理 Vue3 中的“keydown.esc”事件?
【发布时间】:2021-06-20 11:05:34
【问题描述】:

如果变量showModal 为真,我有一个<Parent> 组件,它会呈现<Modal> 组件。

变量showModal<Parent>组件的setup(){}函数中定义。

我想在用户关闭模式时:

  1. 点击关闭按钮
  2. 当他们按下 ESC 按钮时

父组件

<template>
  <Modal v-if="isShownModal" @clickedModalClose="isShownModal=false" @keydown.esc="isShownModal=false">
  //removed some code for clarity purposes
</template>

<script>
export default {
  components: {Modal},
  setup(){

    const isShownModal = ref(false)
    ...

注意@clickedModalClose="isShownModal=false"@keydown.esc="isShownModal=false"

模态组件

<template>

  <div class="modal is-active">
    <div class="modal-background"></div>  
    
    <div class="modal-content box">
      <slot name="header"></slot>
      <slot name="body"></slot>  
    </div>
  
    <!-- Listen to a custom event @clicked-modal-close (v-on) --> 
    <button @click="$emit('clickedModalClose')" class="modal-close is-large" aria-label="close"></button>
  </div>
  
</template>

要关闭模态,当在子组件中单击关闭按钮并监听该事件@clickedModalClose 时,我会发出一个事件,并且正如预期的那样正确关闭模态???

尽管如此,当我点击 ESC 按钮时,即使我在 Modal 组件上声明了事件处理程序,也没有任何反应:&lt;Modal v-if="isShownModal" @clickedModalClose="isShownModal=false" @keydown.esc="isShownModal=false"&gt;

我还尝试将@keydown.esc="closeTheModal()" 附加到&lt;Modal&gt; 中的DIV 和template 标记,然后在closeTheModal() 函数中以编程方式发送clickedModalClose 事件,但无济于事

请问有人可以解释一下这个问题吗:/

更新

正确答案由@blackgreen给出

在渲染组件后,为了处理 ESC 事件,该事件必须附加到组件内的 DOM 元素。

我所做的只是在模态关闭按钮上使用模板引用,使其在 onMounted(){} 挂钩中可用,并在其上调用 focus() 方法

父组件

<Modal @keydown.esc="isShownModal=false">

子组件

<template>
<button ref="closingButton" class="modal-close is-large" aria-label="close"></button>
</template>

在JS部分:

<script>
import {ref, onMounted} from 'vue';
export default {
  setup(props, context){
    
    const closingButton = ref(null)
    onMounted(()=>{
      closingButton.value.focus()
    })

    return {closingButton}

  }
}

【问题讨论】:

  • 我在documentation 中找不到@keydown 语句,只有@keyup.esc。但我想这不会解决这个问题。我会将事件处理程序绑定到 window 而不是 &lt;Modal /&gt; 组件。

标签: vue.js vuejs3


【解决方案1】:

绑定@keydown.esc是正确的(demonstrative fiddle)。

但要真正触发事件,声明监听器的元素必须处于焦点。

this fiddle 示例中,mounted 钩子将焦点设置在 &lt;div&gt; 元素上,tabindex=0 (一个技巧,以便它可以获得焦点)。如果您在该 div 获得焦点时按 Esc,您将看到计数器也在增加。

【讨论】:

  • 嗯,有道理...事件必须附加到 DOM 元素才能冒泡...我将在今天晚些时候检查解决方案。干杯!!!
猜你喜欢
  • 1970-01-01
  • 2021-06-06
  • 2021-11-30
  • 1970-01-01
  • 2014-11-29
  • 2015-03-05
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
相关资源
最近更新 更多