如何在vue-cli中自动提交表单?

How to automatically submit a form in vue-cli?

我想在页面加载时提交隐藏表单。由于表单是隐藏的,我不能使用提交按钮。那么如何在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>

vue 组件有生命周期,您可以在应用程序启动时使用“created”或“mounted”方法在开始时提交表单。

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

您可以按如下方式在 mounted 上触发提交按钮:

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>

更新:

由于表单是使用 v-html 传递和呈现的,我认为您不能使用 ref。因此,您可以将其替换为 id 并使用 vanillla Javascript 函数来单击按钮:

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