lesovsky
lesovsky

Reputation: 346

Handle VueJS event only when key is pressed

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.

Upvotes: 2

Views: 1209

Answers (2)

Dan
Dan

Reputation: 63059

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

Upvotes: 2

Paul
Paul

Reputation: 9

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.

Upvotes: 0

Related Questions