这是我的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,如果我只更新文本输入而不发布表单,则有效)。
答案 0 :(得分: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>