StefanJ
StefanJ

Reputation: 25

Updated form input not posting new value

Here's from my Vue template:

<form action="[path]/post.php" ref="vueForm" method="post">
<input type="hidden" name="hiddenfield" :value="newValue">
<input type="button" value="new value and submit" @click="changeVal(456)">
</form>

[..]

data() {
    return {
      newValue: 123
    }
  },

[..]

methods: {
    changeVal (value) {
      this.newValue = value
      this.$refs.vueForm.submit()
    }
  }

And the PHP file:

$getinfo = $_REQUEST['hiddenfield'];
echo $getinfo;

Posting works fine, but PHP prints 123. I wonder why it's not posting the new value (which should be 456, which works if I only update a text input without posting the form).

Upvotes: 2

Views: 431

Answers (1)

acdcjunior
acdcjunior

Reputation: 135742

DOM updates are asynchronous. You have to wait until the next update cycle updates the DOM:

  methods: {
    changeVal(value) {
      this.newValue = value;
      Vue.nextTick(() => {
        this.$refs.vueForm.submit()
      })
    }
  }

Relevant excerpt from the official docs:

Async Update Queue

In case you haven’t noticed yet, Vue performs DOM updates asynchronously. Whenever a data change is observed, it will open a queue and buffer all the data changes that happen in the same event loop.

Evidence/Demo:

new Vue({
  el: '#app',
  data: {
    newValue: 123
  },
  methods: {
    changeVal(value) {
      this.newValue = value;
      console.log('before nextTick, input:', document.getElementById('ipt').value)
      console.log('before nextTick, txt:', document.getElementById('txt').innerText)
      console.log('before nextTick, WOULD HAVE SUBMITTED');
      Vue.nextTick(() => {
        console.log('after nextTick, input:', document.getElementById('ipt').value)
        console.log('after nextTick, txt:', document.getElementById('txt').innerText)
        console.log('after nextTick, WOULD HAVE SUBMITTED');
        //this.$refs.vueForm.submit()
      })
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <span id="txt">{{ newValue }}</span>

  <form action="[path]/post.php" ref="vueForm" method="post">
    <input id="ipt" type="hidden" name="hiddenfield" :value="newValue">
    <input type="button" value="new value and submit" @click="changeVal(456)">
  </form>
</div>

Upvotes: 1

Related Questions