【发布时间】:2020-12-20 05:02:33
【问题描述】:
我有 2 个组件。
父组件:
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)。尽管子组件的道具在开发工具中是反应性的(计数器 = 9),但它在提交表单时不会反映。但是如果我通过子组件上的提交按钮提交表单(即提交到/test.php?counter=9),它确实有效。
感谢您的帮助。请帮助我理解为什么会出现这种行为并寻求解决方案。
提前致谢。
【问题讨论】:
-
如果提交信号来自父组件,为什么你的子组件有提交按钮?
标签: javascript vuejs2 vue-component vue-props