telion
telion

Reputation: 1120

How do catch the Enter Event on a non-input element in vue?

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.

Upvotes: 1

Views: 1001

Answers (2)

Maik Lowrey
Maik Lowrey

Reputation: 17586

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

methods: {
  handleConfirm(event) {}
}

Upvotes: 0

Arezou Saremian
Arezou Saremian

Reputation: 508

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>

Upvotes: 2

Related Questions