I am using Vue.js in my app and have a text input within a form
我使用Vue。在我的app中有一个文本输入
<div id="myVueForm">
<form>
<input type="text" v-on="keyup:addCategory | key 'enter'">
<!-- more form fields -->
<button type="submit">Submit Form</button>
</form>
</div>
In my Vue instance I have the following
在我的Vue实例中,我有如下内容。
new Vue({
el: '#myVueForm',
methods: {
addCategory: function(e)
{
if(e) e.preventDefault();
console.log("Added a new category, thanks!");
}
}
});
Despite the preventDefault();
call, when a user presses enter whilst on the text input the form still submits (although the addCategory()
method does fire). This behaviour can be demonstrated in this fiddle.
尽管preventDefault();调用,当用户按enter时,窗体仍然提交(尽管addCategory()方法会触发)。这种行为可以用这把小提琴来证明。
I know I can use jQuery to catch the event and prevent the submit, but I'd like to see if it's possible in Vue to do this as it seems quite a common usage.
我知道我可以使用jQuery捕获事件并阻止提交,但是我想看看在Vue中是否有可能这样做,因为这似乎是一个很常见的用法。
5 个解决方案
#1
22
The submit is always fired on keydown. So use keydown instead of keyup.
提交总是在keydown上被触发。所以使用keydown而不是keyup。
<input type="text" v-on="keydown:addCategory | key 'enter'">
#2
19
Here's a solution for Vue.js 2.x:
这是Vue的一个解决方案。js 2. x:
<input type='text' v-on:keydown.enter.prevent='addCategory' />
#3
12
why dont just disable the form submission ?
为什么不禁用表单提交?
<form v-on:submit.prevent><input .../></form>
#4
7
Vue.js 1.0 you could do:
Vue。js 1.0可以做到:
<input type="text" @keyup.enter.prevent="addCategory">
#5
0
You can get event from the HTML and send it to Vue just to preventDefault like so:
您可以从HTML获取事件并将其发送到Vue,以防止出现如下情况:
HTML
HTML
<input type="text" v-on:keydown.13="my_method($event)">
JS
JS
methods: {
my_method(event){
// do something
if (event) event.preventDefault();
if (event) event.stopPropagation();
},
},
#1
22
The submit is always fired on keydown. So use keydown instead of keyup.
提交总是在keydown上被触发。所以使用keydown而不是keyup。
<input type="text" v-on="keydown:addCategory | key 'enter'">
#2
19
Here's a solution for Vue.js 2.x:
这是Vue的一个解决方案。js 2. x:
<input type='text' v-on:keydown.enter.prevent='addCategory' />
#3
12
why dont just disable the form submission ?
为什么不禁用表单提交?
<form v-on:submit.prevent><input .../></form>
#4
7
Vue.js 1.0 you could do:
Vue。js 1.0可以做到:
<input type="text" @keyup.enter.prevent="addCategory">
#5
0
You can get event from the HTML and send it to Vue just to preventDefault like so:
您可以从HTML获取事件并将其发送到Vue,以防止出现如下情况:
HTML
HTML
<input type="text" v-on:keydown.13="my_method($event)">
JS
JS
methods: {
my_method(event){
// do something
if (event) event.preventDefault();
if (event) event.stopPropagation();
},
},