4

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?

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.