Vue.js comes with many key code names out of the box. That means, you can use something like v-on:keyup.enter or @keyup.enter to trigger an event when the Enter key is pressed. I’ve previously written an article on controlled combination of mouse and keyboard key presses to trigger events. Here, in this example I’ll show you how you can register a key code and give it a name, as an alias. You can then access the keycode to trigger any event using the given name.
Here’s my main.js file:
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
Vue.config.keyCodes.f2 = 113;
new Vue({
render: (h) => h(App)
}).$mount("#app");
Code language: JavaScript (javascript)
You’d notice that I’ve added a keyCode as f2 with a value of 113. You can then use the key code in any template as follows:
<template>
<div id="app">
<input v-model="inputValue" v-on:keyup.f2="onF2" />
<div class="np-credits">wwww.nightprogrammer.com</div>
</div>
</template>
<script>
export default {
name: "App",
methods: {
data() {
return {
inputValue: "",
};
},
onF2() {
alert("F2 triggerd!");
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
padding: 24px;
}
.np-credits {
font-size: 12px;
margin-top: 12px;
color: #4b4b4b;
}
</style>
Code language: HTML, XML (xml)
On line 3, I’ve triggered an event (method) called onF2. Whenever a user presses the F2 key from their keyboard, the onF2 method would be invoked. You can find a working demo of the above code from my repo links below: