I am using Vue.js in my app and have a text input within a form
You can use this:
HTML
<form name="..." @submit.prevent="onSubmitMethod">
JS
methods: {
onSubmitMethod() {
}
}
You can use for disable the submit event:
<form @submit.prevent="">
and then when you need to do a form submit use something like this:
<button type="submit" @click="mySubmitMethod"> Send </button>
Vue.js 1.0 you could do:
<input type="text" @keyup.enter.prevent="addCategory">
i wrote a helper for this.
export const preventFormSubmitOnEnter = {
mounted() {
let cb = event => {
if (event) event.preventDefault();
};
if (this.$el.nodeName.toLowerCase() === "form") {
this.$el.onsubmit = cb;
} else {
const forms = this.$el.getElementsByTagName("form");
for (let i = 0; i < forms.length; i++) {
const form = forms[i];
if (form) form.onsubmit = cb;
}
}
}
};
Include this mixin in your vue component and it will automagically work.
here is an example (Im using ElementUI):
<template>
<el-form :model="form" :rules="rules" ref="form">
<el-form-item prop="reference">
<el-input v-model="form.reference" placeholder="Your Reference"/>
</el-form-item>
</el-form>
</template>
<script>
import { preventFormSubmitOnEnter } from "./util";
export default {
mixins: [preventFormSubmitOnEnter],
data() {
return {
form: {
reference: ""
},
rules: {
reference: [{ required: true, message: "Reference is required!" }]
}
};
},
methods: {
validate() {
return new Promise((resolve, reject) => {
this.$refs.form.validate(valid => {
this.$emit("on-validate", valid, this.form);
resolve(valid);
});
});
},
validateField(prop) {
this.$refs.form.validateField(prop);
}
}
};
</script>
For those simply looking to prevent a form submitting on enter, but not wanting to trigger any method on the input, you can simply do:
<input type="text" @keypress.enter.prevent />
Or on a custom component include the native
modifier:
<custom-input type="text" @keypress.enter.native.prevent />
Beautifully readable and succinct.