Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - Handle key press by function in VueJs

in my component I am using VueStrap's modal like this:

<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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...