【发布时间】:2021-06-20 11:05:34
【问题描述】:
如果变量showModal 为真,我有一个<Parent> 组件,它会呈现<Modal> 组件。
变量showModal在<Parent>组件的setup(){}函数中定义。
我想在用户关闭模式时:
- 点击关闭按钮
- 当他们按下 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 组件上声明了事件处理程序,也没有任何反应:<Modal v-if="isShownModal" @clickedModalClose="isShownModal=false" @keydown.esc="isShownModal=false">
我还尝试将@keydown.esc="closeTheModal()" 附加到<Modal> 中的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而不是<Modal />组件。