javascripthtmlvue.js

Can't prevent default on form submission | Vue 3


Using Vue 3.0.5

I have a form:

<form id="app" @submit="onSubmit">
    <input type="text">
    <input type="text">
    <button type="submit">submit</button>
</form>

And a Vue component:

Vue.createApp({
    data() {
        return {}
    },
    methods: {
        onSubmit(e) {
            e.preventDefault();
        }
    }
}).mount('#app');

And can't seem to prevent the page from reloading on form submission. In the version above, I use e.preventDefault() in the method. I've also tried:

Nothing seems to work except reverting to Vue 2. Perhaps an issue with Vue 3 or some quirk I'm missing?


Solution

  • A workaround is to wrap the form in another element, such as a div, and use that as the mount point:

    <script src="https://unpkg.com/vue@3.0.5"></script>
    
    <div id="app">
      <form @submit.prevent="onSubmit">
          <input type="text">
          <input type="text">
          <button type="submit">submit</button>
      </form>
    </div>
    
    <script>
    Vue.createApp({
      methods: {
        onSubmit() {
          console.log('submit')
        }
      }
    }).mount('#app')
    </script>