[Vuejs]-Nuxt.js page reloading on for submission even with stop.prevent

0👍

Ok, I found the answer just by trial and error and it was easier than I thought… It was only about unhandled promise rejection. As I’m using async/await I need to treat exceptions correctly and I was not doing that, the rejection was being propagated and the error handled by nuxt. So changing my code to:

<script>
export default {
  data() {
    return {
      name: '',
      email: ''
    }
  },
  methods: {
    async submit() {
      try {
        const res = await this.$axios.request({
          url: 'locahost:3000/404', // This route doesn't exists
          method: 'post',
          data: this.$data
        })

        console.log(res.status)
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

That will prevent the error to be handled elsewhere and resulting in a redirection to a 404 page or whatever.

1👍

You can omit the form behaviour by only using the data in your submit method and trigger it by @click on the button without any submit type, like this :

<template>
  <div class="container">
    <form>
      <input v-model="name" type="text" />
      <input v-model="email" type="text" />
      <button @click="() => submit()">Submit</button>
    </form>
  </div>
</template>

Like this you will avoid any kind of side effect from the form as you don’t need any form data in your axios request…

👤Hugo T

Leave a comment