12

I'm quite new to Vue and this will be my second dummy project in efforts to learn more about it.

I currently have a form and I am trying to prevent form submission, according to the docs I can do this with v-on:submit.prevent.

I have added this into my form tag, but when submitting the form it is still going through and is not being prevented at all.

I am using Vue version 2.1.3 and below is what I have so far:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Node JS Server</title>
</head>
<body id="chat">
    <form v-on:submit.prevent="send">
        <input>
        <button>Send</button>
    </form>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.6.0/socket.io.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.min.js"></script>

    <script>
        var socket = io();

        new Vue({
            el: '#chat',

            methods: {
                send: function(e) {

                    alert('Send method!');

                }
            }
        })
    </script>
</body>
</html>

What am I doing wrong? As far as I can see from the docs, the form should not submit.

Edit

Here's a fiddle with the code in it

James
  • 15,754
  • 12
  • 73
  • 91

2 Answers2

13

Here is the working fiddle: https://jsfiddle.net/xje4r1u8/2/

You need to make following changes in HTML:

<div id="chat">
    <form v-on:submit.prevent="send">
       <input>
       <button>Send</button>
    </form>
</div>    

in your HTML, you had <body id="chat"> which was causing problem, replacing this with div solved the problem.

Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • 3
    Could you kindly explain what is the relation between a body and the form submission event handler? – realtebo May 30 '19 at 08:14
  • Vue was failing to mount because it does not want `body` used as the root element. So the event handler was never actually assigned. [See docs note for `el`](https://vuejs.org/v2/api/#el). – csum Nov 18 '19 at 18:23
8

This is a strange, but standard-compliant behaviour: If a form only contains one input, it will always submit, and preventDefault() will not prevent that.

See here: Why does a FORM with one text INPUT submit on enter while one with two text INPUTs does not?

Solution: add annother input with type="hidden"

Linus Borg
  • 23,622
  • 7
  • 63
  • 50
  • 1
    A very late comment, but this answer was one of the first googling the problem: this solved my problem. However a input type="hidden" didn't work for me, I'd add a normal input with display:none and that solved the question – Giuseppe Nov 04 '20 at 15:45