Search code examples
vue.jsvue-componentvuejs3vue-reactivityvue-render-function

vue submit form with updated input values


I have a simple hidden form

<template>
  <form ref="form" method="POST" action="https://target.com/post" accept-charset="utf-8">
    <input type="hidden" name="data" :value="myData"/>
    <input type="hidden" name="signature" v-model="mySignature" />
    <input ref="submit" type="submit">
  </form>
</template>

and I want my method which is attached to different button (v-on:click="submitForm")to submit this form setting the data.

export default {
  name: 'MyComponent',
  methods: {
    submitForm() {
      // should update values for inputs
      this.myData = 'dynamically calculated';
      this.mySignature = 'creates signature from data';
      // submit the form with values above
      this.$refs.form.submit();
    },
  },
  data() {
    return {
      myData: null,
      mySignature: null,
    }
  }
}

But seems like I misunderstand reactivity/binding/refs? in Vue, so I've tried

  • this.$refs.submit.click();
  • this.$forceUpdate();
  • setting :value="myData"/ v-model="myData" on inputs

and none of the methods work. Form got sent with empty fields for data/signature, so it seems like variables are not updated or form is not able to rerender within one function call. What's the proper way of doing such an update?


Solution

  • Vue performs DOM updates asynchronously. In your case DOM update does not happen before form submit.

    Workaround is to use $nextTick

    this.$nextTick(() => {
        this.$refs.form.submit();
    });