使用 @keyup 事件输入在 Vue 中不起作用 [英] Enter with @keyup event not working in Vue
问题描述
我正在尝试按回车键调用方法,但它不起作用.代码如下.
<div><button @click="callEvent" @keyup.enter="callEvent">点击</按钮>
</模板><脚本>导出默认{方法:{调用事件(){console.log("事件调用");}}}
click
事件已经用 ENTER 键触发(它也用 Space 在某些浏览器中,例如桌面版 Chrome).因此,您的代码只需要一个 @click="callEvent"
并且一切正常,因为焦点已经在按钮上:
var app = new Vue({el: "#app",方法: {调用事件(){console.log("事件调用");}}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script><div id="应用程序"><button @click="callEvent">回车</button>
如果你想让任何 ENTER 触发按钮,即使它没有焦点,你应该将事件绑定到 window
对象,它可以在里面mounted
处理程序:
var app = new Vue({el: "#app",方法: {调用事件(){console.log("事件调用");}},安装(){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="应用程序"><button>回车</button>
请记住,如果您使用的是单个文件组件,则实例由 this
关键字公开,该关键字可用于在所需的处理程序中调用组件方法:
出口默认{方法: {调用事件(){console.log('事件调用')}},安装(){window.addEventListener('keyup', event => {if (event.keyCode === 13) {this.callEvent()}})}}
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>
The click
event already triggers with the ENTER key (it also triggers with Space in 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:
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 ENTER triggers the button even if it isn't with focus, you should bind the event to the window
object, which can be made inside the mounted
handler:
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 this
keyword, which can be used to call component methods inside the desired handler:
export default {
methods: {
callEvent() {
console.log('Event called')
}
},
mounted() {
window.addEventListener('keyup', event => {
if (event.keyCode === 13) {
this.callEvent()
}
})
}
}
这篇关于使用 @keyup 事件输入在 Vue 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!