我试图将文本字段集中在 ALT + C 快捷方式上(在我的 Electron-Vue 应用程序中):
代码笔: https://codepen.io/anon/pen/aqrBzq?editors=1010
代码笔使用this v-text-field
自定义组件和 this Github 上的评论说,该方法应该用 $nextTick
包裹,以便聚焦此组件
需要这个,但不起作用
<v-text-field
ref="filter"
@keyup.alt.67="focusFilter"
label="type here" >
</v-text-field>
...
methods: {
focusFilter(event){
this.$nextTick(event.target.focus)
}
}
这有效,但不是我需要的:
我也尝试了下面的这段代码,试图用一个按钮来聚焦它,它可以工作,但我想让它与一个快捷键一起工作(例如 ALT + C 但更优选 CTRL + F,但为了示例,我不使用保留的快捷方式)
<v-btn @click="focusFilter()">focus</v-btn>
...
methods: {
focusFilter(event){
this.$nextTick(this.$refs.filter.focus)
}
}
最佳答案
当您在组件上监听 native 事件时,您需要使用 .native
修饰符。
所以改用这个:
@keyup.native.alt.67="focusFilter"
详情在这里:https://v2.vuejs.org/v2/guide/components.html#Binding-Native-Events-to-Components
如果你想在按下 alt+c
时聚焦这个输入并且任何东西都聚焦你需要为 keyup 添加一个事件处理程序到
。window
我创建了一种在适当情况下聚焦它的方法,例如:
methods: {
listenForFocusFilterShortcut (event) {
if (event.keyCode === 67 && event.altKey) {
this.$refs.filter.focus()
}
},
}
然后,添加一个创建的钩子(Hook),并在有 keyup
事件时将此回调附加到窗口。
created () {
window.addEventListener(
'keyup',
this.listenForFocusFilterShortcut
)
},
然后,在移除组件时移除事件监听器:
destroyed () {
window.removeEventListener(
'keyup',
this.listenForFocusFilterShortcut
)
}
关于vue.js - 为什么这个方法不被@keyup 事件触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49101182/