skip to Main Content

I have a form and I should send data to the server by API, but then I want to redirect to the page that I want. Because I use Vue-router, I want to use :to="", it redirects, but doesn’t send data.

<form :action="`/my/api/`" method="post">
  <input name="file" v-model="form.file" type="file" />
  <input name="name" v-model="form.name" label="Name"/>

  <btn label="send" type="submit" v-close-popup/>
</form>

How this issue could be solved?

2

Answers


  1. You can handle this programmatically by putting all the actions you want to execute on submit into a single method and have the form call that method on submit. The below code includes some simplifications and is not the exact code necessary to complete your task. It is just meant to provide a general idea of what to do.

    <form @submit.prevent="submitForm">
      <input />
      <input />
      ...
      <button type="submit">Submit</button>
    </form>
    
    <script>
    export default {
      methods: {
        submitForm() {
          // prepare/validate all form data to be submitted
          const formData = { ... }
          // submit form data
          fetch(url, {
            method: 'POST',
            body: JSON.stringify(formData)
          })
          .then(() => {
            // go to new page
            this.$router.push('/someRoute')
          })
          .catch(() => {
            // handle error
          })
        }
      }
    };
    </script>
    
    Login or Signup to reply.
  2. To achieve the requirement, You have to follow these steps :

    • Instead of directly perform action in the form, You should invoke a method on submit which will responsible to make an API call with the form data.
    • On success response from an API, You can redirect the user to the specific route.

    Template code should be :

    <form>
      <input name="file" v-model="form.file" type="file" />
      <input name="name" type="text" v-model="form.name" label="Name"/>
    
      <button @click="sendFormData">Send</button>
    </form>
    

    In script :

    data: {
      form: {
        file: '',
        name: ''
      }
    },
    methods: {
      sendFormData() {
        // Creating a payload using form fields `v-model`
        const payload = this.form;
        // API call
        fetch(url, {
          method: 'POST',
          body: JSON.stringify(payload)
        })
        .then(() => {
          this.$router.push('<your route>')
        })
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search