Skip to content
Advertisement

Enter key press on with Vue3

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.

Answer

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.

Advertisement