Javascript 使用 Vue.js 从文本输入中按 Enter 时防止表单提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31070479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:10:40  来源:igfitidea点击:

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

javascripthtmlvue.js

提问by harryg

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

我在我的应用程序中使用 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>

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();调用,当用户在文本输入上按下回车键时,表单仍然提交(尽管该addCategory()方法会触发)。这种行为可以在这个 fiddle 中得到证明。

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 中是否可以做到这一点,因为这似乎是一种很常见的用法。

回答by bradlis7

Here's a solution for Vue.js 2.x:

这是 Vue.js 2.x 的解决方案:

<input type='text' v-on:keydown.enter.prevent='addCategory' />

回答by Sebastian Nette

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'">

回答by Clem

why dont just disable the form submission ?

为什么不禁用表单提交?

<form v-on:submit.prevent><input .../></form>

回答by Ryun

Vue.js 1.0 you could do:

Vue.js 1.0 你可以这样做:

<input type="text" @keyup.enter.prevent="addCategory">

回答by Rafael Andrs Cspedes Basterio

You can use this:

你可以使用这个:

HTML

HTML

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

JS

JS

methods: {
  onSubmitMethod() {

  }
}

回答by cjeronimomx

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>

回答by fredrivett

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 nativemodifier:

或者在自定义组件上包含native修饰符:

<custom-input type="text" @keypress.enter.native.prevent />

Beautifully readable and succinct.

可读性强且简洁。

回答by Yevgeniy Afanasyev

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();
    },
},

回答by Stefan Quy

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.

在你的 vue 组件中包含这个 mixin,它会自动工作。

here is an example (Im using ElementUI):

这是一个示例(我使用 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>

回答by modeissey

This works

这有效

 <input type="text" class="form-control" v-model="get_user" @keydown.enter.prevent = "">