How to capture any keypress event in Vuejs without using input element

血红的双手。 提交于 2019-12-10 16:29:46

问题


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">

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', '');
        }
    }
}

There are three ideas I thought of :

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

  2. 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.

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

Any help will be appreciated.

Thanks.


回答1:


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
    });
}


来源:https://stackoverflow.com/questions/40283406/how-to-capture-any-keypress-event-in-vuejs-without-using-input-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!