Categories
Vue Answers

How to Do Something When Hit the Enter Key in Vue.js?

Spread the love

Sometimes, we want to do something when we hit the enter key in Vue.js.

In this article, we’ll look at how to do something when we hit the enter key in Vue.js.

Do Something When Hit the Enter Key in Vue.js

We can do something when we hit the enter key by adding the v-on:keyup directive to the element that does something when we hit the enter key.

For instance, we can write:

<template>
  <div id="app">
    <input v-on:keyup.enter="onEnter" />
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    onEnter() {
      console.log("pressed enter");
    },
  },
};
</script>

We add the v-on:keyup directive with the enter modifier to let us watch for enter key presses.

We set its value to the onEnter method to run it when we focused on the input and press enter.

Also, we can shorten this slightly by using @ instead of v-on: .

To do this, we write:

<template>
  <div id="app">
    <input @keyup.enter="onEnter" />
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    onEnter() {
      console.log("pressed enter");
    },
  },
};
</script>

In either example, we should see 'pressed enter' logged when we focus on the input and press enter.

Conclusion

We can do something when we hit the enter key by adding the v-on:keyup directive to the element that does something when we hit the enter key.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *