How to automatically submit a form in vue-cli?

Viewed 1288

I want to submit a hidden form when the page loads. Since the form is hidden, I can’t use a submit button. So how can I automatically submit a form when the page loads in vuejs?

<template>
  <div v-html="this.paymentResponse"></div>
</template>

<script>
import EventBus from '../../event-bus'

export default {
    data() {
        return {
            paymentResponse: null
        }
    },
    mounted() {
        console.log('mounted')
        this.$refs.submitBtn.click();
    },  
    beforeCreate() {
        EventBus.$on("payment", response => {
            this.paymentResponse = response
        })
    }
}
</script>
2 Answers

You can trigger the submit button on mounted as follows:

new Vue({
     el: '#sg1',
     mounted(){
          this.$refs.submitBtn.click();
     },
     methods:{
          formSumitted(){
               console.log("submitted");
          }
     }
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<div id="sg1">
    <form style="display:none" v-on:submit.prevent="formSumitted">
         <button type="submit" ref="submitBtn">Submit</button>
    </form>
</div>

UPDATE:

Since the form is passed and rendered using v-html, I don't think you can use ref. Therefore, you can replace it with the id and use vanillla Javascript function to click the button:

document.getElementById("submitBtn").click();

The vue components have a lifeCycle, you can use the methods "created" or "mounted" for submit your form at the begining, when your app start.

new Vue({
  data: {
    formData: 'some data'
  },
  created: function () {
    // here your code for submit the form
    
  }
})
Related