Search code examples
vue.js

Call same handler for different events


For accessibility, it is often needed to perform the same action on mouse-click and on pressing enter or space on the keyboard. What is the best way handle those events on a given element?

For example:

<div @click="doTheThing" @keyup.enter="doTheThing" tabindex="0">Do the Thing</div>

Is there a better way to call the the event handler without having the multiple listeners?


Solution

  • A directive to the rescue:

    Playground

    <script setup>
    
    const vAction = (el, {value}) => {
      el.addEventListener('click', value);
      el.addEventListener('keyup', e => e.key==='Enter' && value());
    }
    
    function doTheThing(){
      alert('do the thing');
    }
    </script>
    
    <template>
    
    <div v-action="doTheThing" tabindex="0">Do the Thing</div>
    
    </template>