javascript 使用 @keyup 事件输入在 Vue 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46955147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:03:50  来源:igfitidea点击:

Enter with @keyup event not working in Vue

javascriptvue.js

提问by Hitendra

I am trying to call method on pressing enter key but it's not working. Code is as below.

我正在尝试按回车键调用方法,但它不起作用。代码如下。

<template>
  <div>
    <button @click="callEvent" @keyup.enter="callEvent"> Click </button>
  </div>
</template>

<script>
export default{
  methods:{
    callEvent(){
      console.log("Event called");
    }
  }
}
</script>

采纳答案by Erick Petrucelli

The clickevent already triggers with the ENTERkey (it also triggers with Spacein some browsers, like Chrome for desktop). So, your code only needs a @click="callEvent"and everything works well since the focus is already on the button:

click事件已通过ENTER键触发(它也在Space某些浏览器中触发,例如桌面版 Chrome)。因此,您的代码只需要 a@click="callEvent"并且一切正常,因为焦点已经在按钮上:

var app = new Vue({
  el: "#app",
  methods: {
    callEvent() {
      console.log("Event called");
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
  <button @click="callEvent">Enter</button>
</div>

If you want that any ENTERtriggers the button even if it isn't with focus, you should bind the event to the windowobject, which can be made inside the mountedhandler:

如果您希望任何ENTER触发按钮,即使它没有焦点,您应该将事件绑定到window对象,这可以在mounted处理程序中进行:

var app = new Vue({
  el: "#app",
  methods: {
    callEvent() {
      console.log("Event called");
    }
  },
  mounted() {
    window.addEventListener('keyup', function(event) {
      if (event.keyCode === 13) { 
        app.callEvent();
      }
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
  <button>Enter</button>
</div>

Remember that if you're using Single File Components, the instance is exposed by the thiskeyword, which can be used to call component methods inside the desired handler:

请记住,如果您使用的是Single File Components,则该实例由this关键字公开,该关键字可用于调用所需处理程序内的组件方法:

export default {
  methods: {
    callEvent() {
      console.log('Event called')
    }
  },
  mounted() {
    window.addEventListener('keyup', event => {
      if (event.keyCode === 13) { 
        this.callEvent()
      }
    })
  }
}

回答by Jeff Beagley

I experienced inconsistent results when using native JS with window.addEventListener. VueJS natively supports modifying behavior for keyboard events https://vuejs.org/v2/guide/events.html#Key-Modifiers

在使用带有 window.addEventListener 的原生 JS 时,我遇到了不一致的结果。VueJS 原生支持修改键盘事件的行为https://vuejs.org/v2/guide/events.html#Key-Modifiers

This also worked a lot better in my case due to needing separate behavior for the tab key.

由于需要单独的 Tab 键行为,这在我的情况下也工作得更好。

Your input can look like this with custom modifiers on each key up|down

您的输入看起来像这样,每个键上都有自定义修饰符 up|down

    <input 
        type="text" 
        class="form-control" 
        placeholder="Start typing to search..." 
        v-model="search_text" 
        @focus="searchFocus" 
        @blur="searchFocusOut"
        v-on:keyup.enter="nextItem"
        v-on:keyup.arrow-down="nextItem"
        v-on:keyup.arrow-up="nextItem"
        v-on:keydown.tab="nextItem"
    >

Then inside NextItem you can reference the event, and get each key.. or write a separate function for each key modifier.

然后在 NextItem 中,您可以引用该事件,并获取每个键……或为每个键修饰符编写一个单独的函数。

回答by Nisarg

Buttons don't have keyup event on them. Even when you have focus on the button, and hit enter, it will be considered a click event, instead of keyup.enter.

按钮上没有 keyup 事件。即使当您将焦点放在按钮上并按 Enter 键时,它也会被视为单击事件,而不是keyup.enter

Try binding the event to an input and it'd work.

尝试将事件绑定到输入,它会起作用。

Alternatively, you could use jQuery (or Plain JS) to bind for keydown event on the bodyelement, and trigger the Vue method by calling app.callEvent().

或者,您可以使用 jQuery(或普通 JS)绑定body元素上的 keydown 事件,并通过调用app.callEvent().

var app = new Vue({
  el: "#app",
  methods: {
    callEvent() {
      console.log("Event called");
    }
  },
  mounted() {
    var self = this;
    window.addEventListener('keyup', function(event) {
      if (event.keyCode === 13) { 
        self.callEvent();
      }
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
  <template>
  <div>
    <button @click="callEvent"> Click </button>
  </div>
  <input type="text"  @keyup.enter="callEvent" />
</template>

</div>

Updated to use mountedinstead of relying on jQuery - as per Erick Petrucelli's answeras it allows referring to the Vue component without the global variable.

更新为使用mounted而不是依赖 jQuery -根据 Erick Petrucelli 的回答,因为它允许在没有全局变量的情况下引用 Vue 组件。