3
votes

I'm trying to focus a text field on ALT + C shortcut (in my Electron-Vue app):


Codepen: https://codepen.io/anon/pen/aqrBzq?editors=1010

The codepen uses this v-text-field custom component and as this comment on Github says, the method should be wrapped with $nextTick in order to focus this component


Need this, but doesn't work

 <v-text-field
   ref="filter"
   @keyup.alt.67="focusFilter" 
   label="type here" >
 </v-text-field>

 ...

 methods: {
   focusFilter(event){
     this.$nextTick(event.target.focus)
   }
 }

This works, but is not what I need:

I also tried this code below, trying to focus it with a button, and it works, but I want to make it work with a key shortcut (for example ALT + C but more preferably CTRL + F, but for the sake of example I don't use reserved shortcut)

 <v-btn @click="focusFilter()">focus</v-btn>

 ...

 methods: {
   focusFilter(event){
     this.$nextTick(this.$refs.filter.focus)
   }
 }
1

1 Answers

5
votes

When you're listening for a native event on a component you need to use the .native modifier.

So use this instead:

@keyup.native.alt.67="focusFilter"

Details here: https://vuejs.org/v2/guide/components.html#Binding-Native-Events-to-Components


If you want to focus this input when alt+c is pressed and anything is focused you'd need to add an event handler to window for keyup.

I'd created a method to focus it under the right circumstances like:

methods: {
  listenForFocusFilterShortcut (event) {
    if (event.keyCode === 67 && event.altKey) {
      this.$refs.filter.focus()
    }
  },
}

Then, add a created hook and attach this callback to the window when there's a keyup event.

created () {
  window.addEventListener(
    'keyup',
    this.listenForFocusFilterShortcut
  )
},

Then, remove the event listener when the component is removed:

destroyed () {
  window.removeEventListener(
    'keyup',
    this.listenForFocusFilterShortcut
  )
}