我有两个部件。
父组件:
Vue.component('parent', {
template: '<div><child :counter="counter" :isSubmit="isSubmit" showButton="true"></child>'+
'<button v-on:click="changeCounter">Change Counter</button></div>',
data () {
return {
counter: 2,
isSubmit : false
}
},
methods : {
changeCounter () {
//retrieve value of counter dynamically let's say through ajax call.
this.counter = 9;
this.isSubmit = true;
}
}
})儿童部分:
Vue.component('child', {
template: '<form action="test.php" method="GET" ref="childForm">'+
'<input type="hidden" v-model="counter" name="counter" />'+
'<input type="submit" v-if="showButton" /></form>',
props: {
counter : {
type: Number,
default: 0
},
showButton:false,
isSubmit: false
},
watch : {
isSubmit (val) {
console.log("Inside watcher");
this.submitForm();
}
},
methods : {
submitForm () {
console.log(this.counter);// output-9
this.$refs.childForm.submit();
},
}
})index.html
....
<div id="app>">
<parent></parent>
<parent></parent>
</div>
....在本例中,当我单击“更改计数器”按钮时,表单将使用计数器的旧值提交(即提交给/test.php?counter=2)。虽然子组件的道具在dev tools中是反应性的(计数器= 9),但它在提交表单时没有反映出来。但是,如果我通过子组件上的submit按钮(即提交到/test.php?counter=9)提交表单,那么它确实有效。
谢谢你的帮助。请帮助我理解为什么会出现这种行为,并寻求解决办法。
提前谢谢。
发布于 2020-09-01 05:15:06
速记
因为您使用的是GET请求,所以可以跳过整个<form>,直接转到URL
methods: {
changeCounter () {
this.counter = 9
window.location = `test.php?counter=${this.counter}`
}
}较长答案
您需要等待counter更改来更新DOM,以便使用正常的表单提交。
若要等待状态更改以影响DOM,请使用$nextTick。我还建议通过submitForm方法提交表单,而不是观察布尔值。您可以使用参考文献来访问该方法。
Vue.component('child', {
template: `<form action="test.php" method="GET" ref="childForm">
<input type="hidden" :value="counter" name="counter" />
<input type="submit" v-if="showButton" />
</form>`,
props: {
counter : {
type: Number,
default: 0
},
showButton: Boolean
},
methods: {
async submitForm () {
await this.$nextTick() // wait for the DOM to update
this.$refs.childForm.submit()
}
}
})Vue.component("parent", {
template: `<div>
<child :counter="counter" :show-button="true" ref="form"></child>
<button @click="changeCounter">Change Counter</button>
</div>`,
data: () => ({ counter: 2 }),
methods: {
changeCounter () {
this.counter = 9
this.$refs.form.submitForm() // call the child component method
}
}
})https://stackoverflow.com/questions/63681597
复制相似问题