javascript 在VueJs中按功能处理按键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50395674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handle key press by function in VueJs
提问by Denis Stephanov
in my component I am using VueStrap's modal like this:
在我的组件中,我使用的是 VueStrap 的模态,如下所示:
<template>
<modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed="close()" ... >
...
</modal-window>
...
</template>
<script>
...
methods: {
keyHandler (event) {
console.log(event);
}
},...
</script>
I want handle key press when that modal is opened and ensure submit modal when enter pressed or close modal when esc pressed.
我想在该模式打开时处理按键,并确保在按下输入时提交模式或在按下 esc 时关闭模式。
I added custom function keyHandler which is unfortunately never fired. Can you tell me how to fix code to handle key press in that function? Or when is better way how to close and submit vue strap modal I will be grateful for advice. Thank you.
我添加了自定义函数 keyHandler 不幸的是从未被解雇。你能告诉我如何修复代码来处理那个函数中的按键吗?或者什么时候关闭和提交 vue 表带模式的更好方法我将不胜感激。谢谢你。
回答by Amr Noman
You can attach your event handler to window, that way you can receive all key events and act accordingly depending on your modal's state:
您可以将事件处理程序附加到window,这样您就可以接收所有关键事件并根据您的模态状态采取相应的行动:
Vue.component('modal', {
template: '<div>test modal</div>',
});
new Vue({
el: "#app",
created() {
window.addEventListener('keydown', (e) => {
if (e.key == 'Escape') {
this.showModal = !this.showModal;
}
});
},
data: {
showModal: true
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<modal v-show="showModal"></modal>
</div>

