You can control how a button or an element is click on with Vue.js. Please not that this functionality won’t work on mobile and tablet devices as they might not register key codes for the clicks / key presses.
You can trigger a on click method only when the user presses Ctrl and then clicks on the button with:
<button @click.ctrl="onClick">Ctrl + Click me</button>
Code language: HTML, XML (xml)
You can use other key switches as well:
<button @click.alt="onClick">Alt + Click me</button>
Code language: HTML, XML (xml)
In both the examples however, the click event would get triggered even with multiple key combinations. That is, @click.ctrl would still work if you press Ctrl + Shift and then click on the button. To prevent that from happening, you can use the .exact modifier:
<button @click.ctrl.exact="onClick">Ctrl exact + Click me</button>
Code language: HTML, XML (xml)
You can also accept mouse click buttons with .left, .right and .middle for left, right and middle mouse button clicks respectively.
Here’s some code to demonstrate the example below:
<template>
<div id="app">
<button @click.ctrl="onClick">Ctrl + Click me</button>
<button @click.alt="onClick">Alt + Click me</button>
<button @click.ctrl.exact="onClick">Ctrl exact + Click me</button>
<button @click.left="onClick">Left mouse button</button>
<button @click.right="onClick">Right mouse button</button>
<button @click.middle="onClick">Middle mouse button</button>
<div class="np-credits">wwww.nightprogrammer.com</div>
</div>
</template>
<script>
export default {
name: "App",
methods: {
onClick() {
alert("Clicked!");
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
padding: 24px;
}
button {
margin-top: 0.5em;
background-color: #004cbe;
color: #ffffff;
border: 0px;
border-radius: 6px;
padding: 6px 20px;
margin-right: 1em;
cursor: pointer;
transition: all 0.3s;
}
button:hover {
background-color: #2f79e7;
transition: all 0.3s;
}
.np-credits {
font-size: 12px;
margin-top: 12px;
color: #4b4b4b;
}
</style>
Code language: HTML, XML (xml)
You can find a working demo of the above code from my repos below: