Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 456
stasiekz Avatar asked Oct 23 '25 18:10

stasiekz


1 Answers

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

like image 117
tony19 Avatar answered Oct 26 '25 08:10

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!