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

后端 未结 11 1505
轻奢々
轻奢々 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: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):

    
    
    
    

提交回复
热议问题