Prevent form submitting when pressing enter from a text input, using Vue.js

后端 未结 11 1481
轻奢々
轻奢々 2020-12-13 12:16

I am using Vue.js in my app and have a text input within a form

相关标签:
11条回答
  • 2020-12-13 13:02

    You can use this:

    HTML

    <form name="..." @submit.prevent="onSubmitMethod">
    

    JS

    methods: {
      onSubmitMethod() {
    
      }
    }
    
    0 讨论(0)
  • 2020-12-13 13:03

    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>
    
    0 讨论(0)
  • 2020-12-13 13:04

    Vue.js 1.0 you could do:

    <input type="text" @keyup.enter.prevent="addCategory">
    
    0 讨论(0)
  • 2020-12-13 13:08

    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>
    
    0 讨论(0)
  • 2020-12-13 13:11

    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.

    0 讨论(0)
提交回复
热议问题