Reputation: 346
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
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)
Upvotes: 2
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