Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enter with @keyup event not working in Vue

I am trying to call method on pressing enter key but it's not working. Code is as below.

<template>
  <div>
    <button @click="callEvent" @keyup.enter="callEvent"> Click </button>
  </div>
</template>

<script>
export default{
  methods:{
    callEvent(){
      console.log("Event called");
    }
  }
}
</script>
like image 328
Hitendra Avatar asked Oct 26 '17 13:10

Hitendra


1 Answers

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:

var app = new Vue({
  el: "#app",
  methods: {
    callEvent() {
      console.log("Event called");
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
  <button @click="callEvent">Enter</button>
</div>

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>

Remember that if you're using Single File Components, the instance is exposed by the this keyword, which can be used to call component methods inside the desired handler:

export default {
  methods: {
    callEvent() {
      console.log('Event called')
    }
  },
  mounted() {
    window.addEventListener('keyup', event => {
      if (event.keyCode === 13) { 
        this.callEvent()
      }
    })
  }
}
like image 143
Erick Petrucelli Avatar answered Oct 19 '22 15:10

Erick Petrucelli