我在我的应用程序中使用 Vue.js 并在表单中输入文本
<div id="myVueForm">
<form>
<input type="text" v-on="keyup:addCategory | key 'enter'">
<!-- more form fields -->
<button type="submit">Submit Form</button>
</form>
</div>
在我的 Vue 实例中,我有以下内容
new Vue({
el: '#myVueForm',
methods: {
addCategory: function(e)
{
if(e) e.preventDefault();
console.log("Added a new category, thanks!");
}
}
});
尽管 preventDefault()
调用,当用户在文本输入上按下 enter 时,表单仍会提交(尽管 addCategory()
方法会触发)。此行为可以在 this fiddle 中演示.
我知道我可以使用 jQuery 来捕获事件并阻止提交,但我想看看是否可以在 Vue 中执行此操作,因为这似乎很常见。
最佳答案
这是 Vue.js 2.x 的解决方案:
<input type='text' v-on:keydown.enter.prevent='addCategory' />
关于javascript - 使用 Vue.js 从文本输入中按回车键时防止提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31070479/