最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

vue.js - Call same handler for different events - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Feb 8 at 10:06 Mark Rotteveel 109k226 gold badges155 silver badges219 bronze badges asked Feb 7 at 20:00 Peter HentgesPeter Hentges 354 bronze badges 2
  • 3 Idk if there's a better way to do it on a div, but if it's an element that's normally clickable like a button it seems to work for both if you just set @click – vanblart Commented Feb 7 at 20:43
  • In addition to click and enter, I started looking for answers to this question based on building a tab component which needs to also listen for arrow key presses for keyboard navigation. The directive example from the accepted answer will help with that. – Peter Hentges Commented yesterday
Add a comment  | 

2 Answers 2

Reset to default 2

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>

The best way to handle these events on a specific element - is when the element is a button.
It will handle click event like @keyup.enter and @keyup.space.
And it will be harmonious with accessibility.

<script setup>
const click = () => {
  alert('click');
}
</script>

<template>
  <button @click="click">Button</button>
</template>

Example

发布评论

评论列表(0)

  1. 暂无评论