我有一个<Parent>组件,如果变量showModal为真,则呈现showModal组件。
变量showModal是在<Parent>组件的setup(){}函数中定义的。
当用户:
父组件
<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元素。
我所做的就是简单地使用Modal关闭按钮上的模板引用,使其在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}
}
}https://stackoverflow.com/questions/66769162
复制相似问题