[英]VueJS - Props are not updated in child component by changes in parent
Props are not updated when I change them in parent component 当我在父组件中更改道具时,它们不会更新
Parent component: 父组件:
I have controlData
value as defaul value for child component prop control
which is equal 2
and I can see that value when I run my app first time 我有
controlData
值作为子组件prop control
默认值,等于2
并且在我第一次运行应用程序时可以看到该值
data() {
return {
controlData: 2
}
}
In ready()
I need to load data from back-end and to set that value to child component prop control
equal to the data from back-end. 在
ready()
我需要从后端加载数据并将该值设置为与后端数据相等的子组件prop control
。
But lets say that now I just want to change control
(value in child) when parent component is ready. 但是可以说,现在我只想在父组件准备就绪时更改
control
(子项中的值)。 So I made this in parent component: 所以我在父组件中做了这个:
ready() {
this.controlData = 55;
}
Then I use v-bind to send that value in child when controlData
is changed 然后,当
controlData
更改时,我使用v-bind在子级中发送该值
<child-component :control="controlData"></child-componenet>
Child component: 子组件:
I have this in my child component 我的孩子部分有这个
export default Bar.extend({
props: ["control"],
ready() {
console.log(this.control); // I see only default value "2" not "55" - but I expect to see "55" because I changed that value in ready() of parent
}
})
I added also watch: {}
to look for changes of props
but I can't see the changes 我还添加了
watch: {}
寻找props
变化,但看不到变化
watch: {
control() {
console.log("Control is changed"); // I don't see this message when I change controlData value in parent and then by v-bind:control="controlData" i send that data in child component
}
}
The code you have posted should update the child prop if correctly implemented. 如果正确实施,您发布的代码应更新子道具。
One thing to note, the child's ready() hook will be executed BEFORE the parent ready() hook. 有一点要注意,孩子的准备()钩子将父就绪()挂钩之前执行。 So you should see the console log the following:
因此,您应该在控制台日志中看到以下内容:
2
Control is changed
This is working for me using Vue 1.0.28: 这对我使用Vue 1.0.28起作用:
https://codepen.io/camaulay/pen/wejpPa?editors=1011 https://codepen.io/camaulay/pen/wejpPa?editors=1011
JS: JS:
var child = Vue.extend({
template: '<div>Child data: {{ control }}</div>',
props: ['control'],
ready () {
console.log(this.control);
},
watch: {
control () {
console.log("Control is changed")
console.log(this.control)
}
}
})
var app = new Vue({
el: '#app',
components: {
'child': child
},
data () {
return {
controlData: 2
}
},
ready () {
this.controlData = 55
}
})
HTML: HTML:
<div id="app">
<child :control="controlData"></child>
<button @click="controlData++">Increment parent data</button>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.