【问题标题】:Why isn't this method getting triggered by a @keyup event?为什么@keyup 事件不会触发此方法?
【发布时间】:2018-08-12 13:27:16
【问题描述】:

我正在尝试将文本字段集中在 ALT + C 快捷方式(在我的 Electron-Vue 应用中):


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

codepen 使用 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)
   }
 }

【问题讨论】:

    标签: vue.js vuejs2 vuetify.js


    【解决方案1】:

    当您在组件上侦听本机事件时,您需要使用 .native 修饰符。

    所以改用这个:

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

    详情请看:https://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()
        }
      },
    }
    

    然后,添加一个 created 钩子,并在有 keyup 事件时将此回调附加到窗口。

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

    然后,在移除组件时移除事件监听器:

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

    【讨论】:

    • 感谢您的回答。虽然还是不行。你能检查一下codepen吗,你在那里看到任何其他错误吗?也许在methods: { }
    • this.$nextTick(event.target.focus) 不对,应该是this.$nextTick(() =&gt; event.target.focus())event.target.focus 不会返回 $nextTick 期望的函数。如果您查看添加了 .native 修饰符的控制台,您将看到无效调用。
    • 奇怪的是,只有当我手动聚焦文件然后按ALT + C 时,它才会给我“非法调用”。就好像它在被选中之前甚至不会监听ALT + C。那有什么意义呢
    • 您需要在窗口上等待该事件。 keyup 只会在“活动”元素上触发,然后冒泡到窗口,除非你停止它。我将在我的答案中添加我将如何处理它。
    • 很好,现在可以使用了。感谢您帮助我(可能还有其他人)理解它并提供实际有效的示例代码!
    猜你喜欢
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    相关资源
    最近更新 更多