Home  >  Q&A  >  body text

Add keyboard shortcuts for buttons in vuejs

I have a button that performs certain actions when clicked with the mouse. I want the same method to be triggered when the keyboard's up arrow key is pressed.

<button @click="doSomething()"> PRESS ME </button>

doSomething(){
  console.log('clicked')
}

So in this example, I want to console.log('clicked') when the keyboard's up arrow is pressed. How can I do this?

P粉771233336P粉771233336289 days ago410

reply all(2)I'll reply

  • P粉031492081

    P粉0314920812024-01-05 10:06:30

    hope it helps you.

    doSomething(){
      console.log('clicked')
    }
    
    var buttonBtn = document.getElementById("btn");
    buttonBtn.addEventListener("keyup", function(event) {
      event.preventDefault();
      this.doSomething();
    });
    <button id="btn" @click="doSomething()"> PRESS ME </button>

    reply
    0
  • P粉994092873

    P粉9940928732024-01-05 00:54:05

    You can use onkeyrinkle from vueuse

    <template>
      <div>
        <button @click="doSomething">btn</button>
      </div>
    </template>
    
    <script setup>
    import { onKeyStroke } from '@vueuse/core';
    
    const doSomething = () => {
      console.log('do something');
    }
    
    onKeyStroke(['ArrowUp'], (e) => {
      doSomething();
    });
    </script>

    Here is another demo

    stackblitz.com does not support