Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • @submit.prevent instead of manually calling e.preventDefault()
  • v-on:submit while calling e.preventDefault()
  • v-on:submit.prevent without calling
  • @submit.prevent/v-on:submit.prevent and manually calling at the same time

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

like image 999
jonxola Avatar asked Jan 26 '26 00:01

jonxola


1 Answers

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/[email protected]"></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>
like image 74
tony19 Avatar answered Jan 28 '26 12:01

tony19