admin管理员组

文章数量:1325510

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.

本文标签: javascriptEnter key press on ltligt with Vue3Stack Overflow