2

In VueJS, there are event modifiers for click and key events that allow things like click.prevent, click.once, key.up.

How do I create custom event modifiers?

More specifically, how can I create a mousemove.throttle event modifier so that I can apply lodash throttling whenever I add that modifier to an event?

jeffjenx
  • 17,041
  • 6
  • 57
  • 99

1 Answers1

4

One of the options is to create a custom directive similar to this one

Vue.directive('throttled-on', {
  bind(el, binding, vnode) {
    const handler = throttle(1000, binding.value)
    let type = binding.arg

    el.addEventListener(type, handler)
  }
})

var app = new Vue({
  el: '#app',
  methods: {
    myMethod() { console.log('Called') }
  }
})
<script src="https://cdn.jsdelivr.net/npm/throttle-debounce@2.1.0/dist/index.cjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div >
  <div
    id="app"
    style="width: 100px; height: 100px; background: red;"
    v-throttled-on:mousemove="myMethod"
  />
 </div>
NaN
  • 1,955
  • 13
  • 16
  • Thanks for the answer. So, basically, you are suggesting to abandon the idea of a custom event modifier and instead use a custom directive to solve the same problem. That seems like a logical alternative. Out of curiosity, is it even possible to create custom event modifiers on custom directives other than Vue's `v-on` directive? – jeffjenx Jul 21 '19 at 18:23
  • It is an interesting question and I don't know. Will be glad if someone can show how to achieve it – NaN Jul 21 '19 at 18:30
  • Looks like you can using `binding.modifiers`. It's worth noting that the modifiers are Boolean states, so creating a throttled event might be a bit more difficult than I anticipated since the throttled wait time value would have to be static. Doesn't appear to be able to use modifiers on normal events, though, since you can't hook into the native `v-on` directive. – jeffjenx Jul 22 '19 at 15:51