George A
George A

Reputation: 39

Key modifier on parent of component

Is there a way to record a tab event of a component without having access to the child component?

for example:

in the Parent:

<inputcomponent
    label="mylabel"
    placeholder="myplaceholder "
    v-on:keydown.tab="keydown($event)"    <---
    >
</inputcomponent>

I have downloaded an autocomplete component from a library so I would like to find a way to record the "tab" event without changing the component, but the parent.

Is it possible?

Upvotes: 0

Views: 38

Answers (1)

Daniel
Daniel

Reputation: 35724

It depends on the component. if the component is not set up to emit listeners, you won't be able to listen to the events this way.

If you cannot edit the component itself, you can go around it by adding custom event listeners during mount (and clearing them on remove)

here is an example that assumes: - you have a component with a ref="componentA" in template - you have a function called onTab - you clear the listener using appropriate event lifecycle

  mounted () {
    window.addEventListener('keydown', (e) => {
      if (e.key === 'Tab'){
        var el = e.target;
        while (el) {
          if (el === this.$refs.componentA) {
            // do my action
            return this.onTab();
          }
          el = el.parentElement
        }
      }
    })
  }

This will add an event listener at window level, which will listen to the tab key pressed on ANYTHING. However, the target element is recursively compared to your current element. This is not ideal, obviously, since using $emit has lower overhead than looping through any element's parents, which is why clearing this listener is important.

Upvotes: 1

Related Questions