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

javascript - Enter key press on <li> with Vue3 - Stack Overflow

programmeradmin1浏览0评论

Have this code:

<li v-for="(dog, index) in dogs" :key="index" class=" hover:bg-gray-50" :class="{ 'bg-red-50': index === focus }" @keyup.enter="goToSlug(dog)"> .... </li>

I handle the focus perfectly, but want to run the method goToSlug() on key enter be pressed. It doesn't fire the method.

Have this code:

<li v-for="(dog, index) in dogs" :key="index" class=" hover:bg-gray-50" :class="{ 'bg-red-50': index === focus }" @keyup.enter="goToSlug(dog)"> .... </li>

I handle the focus perfectly, but want to run the method goToSlug() on key enter be pressed. It doesn't fire the method.

Share Improve this question edited Jun 1, 2022 at 17:09 Riza Khan 3,1585 gold badges28 silver badges63 bronze badges asked Aug 12, 2021 at 23:38 Louis BLouis B 3061 gold badge6 silver badges20 bronze badges 1
  • You need the li element to have focus, for key events to fire. You can use vuejs refs to set focus to that element. – Bergur Commented Aug 13, 2021 at 0:03
Add a ment  | 

1 Answer 1

Reset to default 6

Key presses are only registered on items that have focus.

In order to make an element like a <li> tag focusable (which natively does not have that ability) you will need to add another attribute called tabindex='1' (1 being an arbitrary value here, but you can read more up on that here).

So in your case:

<li 
  v-for="(dog, index) in dogs" 
  tabindex="1" 
  :key="index" 
  class=" hover:bg-gray-50" 
  :class="{ 'bg-red-50': index === focus }" 
  @keyup.enter="goToSlug(dog)"
> .... 
</li>

Now, in order to register a key press on this (or its siblings) just tab through them and press enter when you have the desired target.

发布评论

评论列表(0)

  1. 暂无评论