darrenjennings / vue-autosuggest

🔍 Vue autosuggest component.
https://darrenjennings.github.io/vue-autosuggest
MIT License
621 stars 91 forks source link

Looks like you preventDefault() no matter popup opened or not #153

Closed Sielc closed 4 years ago

Sielc commented 5 years ago

v2.0.4

Problem:

I have a modal window with vue-autosuggest

<autosuggest
        :suggestions="[{ data: hints }]"

I want vue-autosuggest to preventDefault() only when necessary.

Possible Solution:

File Autosuggest.vue Method handleKeyStroke() For key 13 check if the popup opened or not and do things only if isOpen()

handleKeyStroke() {
  ...
  case 13:
    if (this.isOpen()) {
      e.preventDefault();
      ...

But:

I see there is a check for "ESC" key, but I still receive an event with .defaultPrevented == true

case 27: // Escape
          if (this.isOpen) {
darrenjennings commented 5 years ago

@Sielc thanks for your interest. Can you reproduce in a codesandbox so that I can better assist?

You can fork this one: https://codesandbox.io/s/vueautosuggest-20-base-yij1b

Sielc commented 5 years ago

https://codesandbox.io/s/vueautosuggest-20-base-fw1o1?fontsize=14

defaultPrevented is almost always true

Sielc commented 5 years ago

Also try to press enter when the popup is closed, you'll see

Cannot read property 'item' of null

because you fire @selected with null value

darrenjennings commented 5 years ago

defaultPrevented is almost always true

I think you can use @keydown.capture='keydown' here to accomplish what you want.

because you fire @selected with null value

Thanks for the report there, looks like I need to take another look https://github.com/darrenjennings/vue-autosuggest/issues/149#issuecomment-550035661

Sielc commented 5 years ago

use capture mode when adding the event listener i.e. an event targeting an inner element is handled here before being handled by that element

.capture changes an order of methods, that receive an event. I'd like to keep both features. I updated codesandbox to demonstrate, that capture workaround doesn't work.

darrenjennings commented 5 years ago

Still a little fuzzy how it might work for you, but does putting keydown listeners on the the autosuggest itself help? Then you can can capture the events at the element level and decide what you want to do... close modal or whatever.

https://codesandbox.io/s/vueautosuggest-153-ihxkz

e.g.

<input @keydown.esc="keydown" />
<vue-autosuggest
  ...
  @keydown.esc="keydown" />