2

I use VueJS component provided by 3rd-party library, which has its own events. I can handle such events as usual with "v-on" directive and specifying interesting event name, like that:

<TheComponent v-on:itemchanged="handler"/>

But is it possible to run handler only when 'itemchanged' occurs with CTRL key pressed? The handler should not run when CTRL key is not pressed.

I tried to play with click.crtl and keydown.ctrl but have no success.

lesovsky
  • 326
  • 2
  • 14
  • I found a semi-working solution, I wrapped component into outer div with `v-on:click.ctrl="pressed = true"`. Next in nested component's handler i'm checking 'pressed' variable. It works but only from second click. – lesovsky Nov 11 '20 at 10:26

2 Answers2

2

Is it possible to run handler only when 'itemchanged' occurs with CTRL key pressed?

Assuming itemchanged is triggered by a change event: no, not without a workaround. Unlike keyboard and mouse events, change contains no keyboard info. You'll need to track the status of ctrl keypresses independently because JavaScript has no way of testing whether a key is down outside of those events.

Plugin

One encapsulated way to accomplish it is with a plugin:

const pluginKeypresses = function(Vue) {
  const keyPresses = {
    Control: false
  }
  window.onkeyup = function(e) { keyPresses[e.key] = false; }
  window.onkeydown = function(e) { keyPresses[e.key] = true; }
  Vue.prototype.$keyPresses = Vue.observable(keyPresses);
}
Vue.use(pluginKeypresses);

Note: The e.key detection here is the current standard as of 11/2020, but is not yet fully supported by IE and some other browsers. If IE matters to you, change the key detection implementation to your liking.

Usage

From anywhere in the app you can test this.$keyPresses.Control (boolean)

Demo

Dan
  • 59,490
  • 13
  • 101
  • 110
0

Don't you receive an event object with this event ? By adding a parameter to handler you should be able to catch the event, and check inside which key is pressed. Then just add a if statement at the beginning of you handler function.

Paul
  • 9
  • 4
  • If an appropriate keyboard event `$event` had been passed, then `.ctrl` would have worked – Dan Nov 11 '20 at 09:18
  • yes, i receive event object, but if using "v-on:itemchanged", it doesn't contain any info about pressed keys. If I try to modify it to "v-on:itemchanged.ctrl" or "v-on:click.ctrl" it is not working. At the same time "v-on:click.ctrl" works on simple div element. So I think this component might not support key-based events. – lesovsky Nov 11 '20 at 09:34
  • @lesovsky This is likely because the event is a `change` event, which has no keyboard information – Dan Nov 11 '20 at 09:35