javascriptvue.jsshortcutkeyeventkeyup

adding a keyboard shortcut to your button in vuejs


I have a button that does something when clicking on it with mouse. I want the same method to also be triggered when pressing on your keyboard's up arrow key.

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

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

So in this example I want to console.log('clicked') when pressing on keyboard's up arrow. How can I do that?


Solution

  • you may use onkeystroke 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>
    

    another demo here

    stackblitz.com doesn't support <script setup> so in this demo, it is written in setup()


    update

    pure js without library:

    <template>
        <div>
            <button
                @click="doSomething">
                btn
            </button>
        </div>
    </template>
    
    <script setup>
    import { onMounted, onBeforeUnmount } from 'vue';
    
    const doSomething = () => {
        console.log('doSomething');
    };
    
    const userClickArrowUp = ({ code }) => {
        if (code === 'ArrowUp') {
            doSomething();
        }
    };
    
    onMounted(() => {
        document.addEventListener('keyup', userClickArrowUp, true);
    })
    
    onBeforeUnmount(() => {
        document.removeEventListener('keyup', userClickArrowUp, true);
    })
    
    </script>