stasiekz
stasiekz

Reputation: 1853

How to dynamically assign keyboard events in Vue JS

When I bind keydown event for alt + 1 combination on the main component's element like so:

<div
    @keydown.alt.49.prevent.exact="doSomething()"
>

It works, but when I try to bind it dynamically based on some logic in created (inspired by Programmatically bind custom events for dynamic components in VueJS):

created() {
    this.$on('keydown.alt.49.prevent.exact', doSomething);
},

It does not work. What am I doing wrong?

Upvotes: 4

Views: 1388

Answers (1)

tony19
tony19

Reputation: 138196

The first argument of vm.$on() is the event name, but you've passed it the event name along with the event modifiers, which are only valid in the template.

keydown                 // Event name
.alt.49.prevent.exact   // Event modifiers

An equivalent method that implements the event modifiers would look like this:

export default {
  methods: {
    eventHandler(e) {
      // .alt.49
      //   `keyCode` 49 is deprecated, so use `key` equivalent
      //   for Alt+1: the inverted exclamation point, not '1'
      const isAlt1 = e.altKey && e.key === '¡'

      // .exact
      const isExact = !e.shiftKey && !e.ctrlKey && !e.metaKey

      if (isAlt1 && isExact) {
        // .prevent
        e.preventDefault()

        // this.doSomething()
      }
    }
  }
}

To add that event handler to the div, apply a template ref:

<div ref="myEl"></div>

Then access the element via this.$refs, and use the element's native addEventListener():

this.$refs.myEl.addEventListener('keydown', this.eventHandler)

demo

Upvotes: 6

Related Questions