Home > Back-end >  How do catch the Enter Event on a non-input element in vue?
How do catch the Enter Event on a non-input element in vue?

Time:12-04

I have a confirm Button, that should also be triggered by an Enter-Event.

Basically, I was hoping that this could work:

<someComponent @keyup.enter="handleConfirm" />
...
methods: {
  handleConfirm(event) {
       console.log("works") 
  }
}

But it doesn't. Apparently, this approach only works with input fields.

How can I listen to a keyup Event in Vue on any element/component?

EDIT To clarify: Any element/component even out of focus.

CodePudding user response:

The click event already triggers with the ENTER key (it also triggers with Space in some browsers, like Chrome for desktop). So, your code only needs a @click="callEvent" and everything works well since the focus is already on the button

If you want that any ENTER triggers the button even if it isn't with focus, you should bind the event to the window object, which can be made inside the mounted handler

var app = new Vue({
  el: "#app",
  methods: {
    callEvent() {
      console.log("Event called");
    }
  },
  mounted() {
    window.addEventListener('keyup', function(event) {
      if (event.keyCode === 13) { 
        app.callEvent();
      }
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
  <button>Enter</button>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can do this: <someComponent @keyup.enter="handleConfirm($event)" />

methods: {
  handleConfirm(event) {}
}
  • Related