如何在不使用input元素的情况下捕获Vuejs中的任何按键事件 [英] How to capture any keypress event in Vuejs without using input element

查看:305
本文介绍了如何在不使用input元素的情况下捕获Vuejs中的任何按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一种游戏,我想让用户输入一个特定的单词,然后我想检查是否按下了特定的单词。如果单词被按下,我将获取下一个单词。目前我正在使用表单并使用如下所示的 v-model

I am making kind of game in which I want user to enter a particular word and then I want to check if the particular word is pressed. If the word is pressed I will fetch the next word. Currently I am using a form and have used v-model shown below :

 <input v-model="inputSpell">

在Vue实例中,我使用了 watch 属性,该属性会不断检查如果输入的单词与询问的单词匹配。

In the Vue instance I have used the watch property which constantly checks the if the input word matches the asked word.

watch : {

    inputSpell : function() {
        var spellCount = this.spellCount;
        var inputSpell = this.inputSpell.toUpperCase();
        var presentSpell = this.presentSpell;

        console.log("Spell Count " + spellCount);
        console.log("Input Spell " + inputSpell);
        console.log("Present Spell" + presentSpell);

        if (inputSpell.length === 3 && inputSpell === presentSpell) {
            this.$set(this, 'inputSpell', '');
            if (spellCount === 3) {
                return this.completeCombo();
            }
            return this.fetchSpell(spellCount);
        }

        if (inputSpell.length >=3) {
            this.$set(this, 'inputSpell', '');
        }
    }
}

我认为有三个想法of:

There are three ideas I thought of :


  1. 上面我正在做的是显示表格。用户输入该表单中的单词。看起来不太好看。

  1. Above way what I am doing is showing the form. The user enters for word in that form. Does not look good.

在加载游戏时隐藏输入元素并专注于它。但缺点是如果用户点击页面上的任何地方,表单上的焦点将会丢失。

Make the input element hidden and focus on it when the game loads. But the disadvantage is if the user click anywhere on the page the focus on the form will be lost.

制作自定义指令或调用捕获按键事件以检查单词的方法。

Making a custom directive or calling a method which captures the keypress event to check for words.

任何帮助将不胜感激。

Any help will be appreciated.

谢谢。

推荐答案

要在不使用输入的情况下捕获按键,您可以在生命周期钩子中包含一个标准事件监听器(已挂载 ,例如)像这样:

To capture a key press without using an input, you could just include a standard event listener inside your lifecycle hook ("mounted", for instance) like so:

mounted() {

    let self = this; 

    window.addEventListener('keyup', function(ev) {
        self.myMethod(ev); // declared in your component methods
    });
}

这篇关于如何在不使用input元素的情况下捕获Vuejs中的任何按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆