0

Am trying to programmatically add events using v-on by passing an object with keys as events name and values as handlers.

This method seems not to allow or recognize events modifiers like

v-on=“{‘keydown.enter.prevent’: handler}”

The keydown event above won’t trigger, except the modifiers are removed

v-on=“{keydown: handler}”

Is there a way to make this work?

2 Answers 2

1

Please think of all the things you're losing by doing this. I've never encountered the need, and it strikes me as something you should jump through hoops to avoid.

In the normal case, your template is a dumb stable thing that closely ressembles the output, with holes for dynamic data (supplied via reactivity) and some event handlers that will eventually update your model. It tells you everything it will call.

If you have some code somewhere that dynamically attaches event handlers, or modifies their behaviour, you no longer have that certainty. You attach your handlers in response to what? Your app now has modes, which are bad. I would much rather have static, permanently attached, declared in the template, event handlers, then deal with your requirement by putting conditionals in the handlers.

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

Comments

0

This is how you can use dynamic arguments to bind a handler to a dynamic event name:

const app = new Vue({
  el: '#app',
  data() {
    return {
      event: 'keydown',
    }
  },
  methods: {
    handler() {
      console.log('Called')
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.1/vue.js"></script>
<div id="app">
  <div>Dynamic event with modifiers</div>
  <button @[event].enter.prevent="handler">Listening to: {{ event }}</button>
</div>

Please note:
This syntax is only supported in version 2.6.0+. See the docs here.

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.