vuejs: @keyup.esc on div element is not working

前端 未结 6 623
借酒劲吻你
借酒劲吻你 2021-02-12 12:57

I\'m expecting that \'close\' event is fired when I\'m clicking ESC button being on \"shadow-modal\" div, but it\'s not happening

vue 2.5.13, any ideas why?

6条回答
  •  青春惊慌失措
    2021-02-12 13:50

    While DmitrySemenov solution works for me it's not the best solution when you have multiple modals on the page. I tried it and I discovered it fires close event for every modal.

    I think the best way to do it is registering a "keyup" event when the modal is shown and deregistering it after hide. It gives you an advantage because the event is registered only when it's needed. To do it you need to add a watcher for "show" property:

      props: {
        show: {
          type: Boolean,
          default: false
        }
      },
      watch: {
        show() {   
          if (this.show === false) {
            window.removeEventListener("keyup", this.onEscapeKeyUp);
          } else {
            window.addEventListener("keyup", this.onEscapeKeyUp);
          }
        }
      },
      methods: {
        onEscapeKeyUp(event) {
          if (event.which === 27) {
            this.$emit("close");
          }
        }
      }
    

    The modal should have v-if="show" that controls modal's visibility:

    Whole solution code (you can see it on codesandbox.io):

    Modal.vue

    
    
    
    
    
    

    App.vue

    
    
    
    

提交回复
热议问题