【问题标题】:Updated form input not posting new value更新的表单输入未发布新值
【发布时间】:2018-04-18 23:35:45
【问题描述】:

这是我的 Vue 模板:

<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()
    }
  }

还有 PHP 文件:

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

发布工作正常,但 PHP 打印 123。我想知道为什么它没有发布新值(应该是 456,如果我只更新文本输入而不发布表单,它会起作用)。

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    DOM 更新是异步的。您必须等到下一个更新周期更新 DOM:

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

    相关excerpt from the official docs

    异步更新队列

    如果你还没有注意到,Vue 会执行 DOM 更新 异步。每当观察到数据变化时,它将打开一个 排队并缓冲同一事件中发生的所有数据更改 循环。

    证据/演示:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 2017-08-20
      • 2017-02-15
      • 2020-12-05
      • 2013-08-30
      相关资源
      最近更新 更多