My project has one parent and child component. Parent component has one state and I want to increase it in a time interval. Child component inherits the state and prints value on console in a time interval. My problem is child component gets the state value only when it is first created. It doesn't get updated.
我的项目有一个父组件和子组件。父零部件有一种状态,我想在某个时间间隔内增加它。子组件在一段时间间隔内继承状态并在控制台上打印值。我的问题是,子组件只有在第一次创建时才获得状态值。它不会更新。
Expected Output: 0 1 2 ...
预期输出:0 1 2...
My Output: 0 0 0 ...
我的输出:0 0...
How can I update the child component when I change the state of the parent component. I tried updated() and watch in the child component with putting log in there. It doesn't enter those places at all. My code is shown below. Can you help?
更改主零部件的状态时,如何更新子零部件。我尝试更新()并在子组件中查看,并将日志放入其中。它根本不会进入那些地方。我的代码如下所示。你能帮忙吗?
App.vue
App.vue
<template>
<div id="app">
<ChildComponent :state="state"/>
</div>
</template>
<script>
import ChildComponent from './components/ChildComponent.vue'
export default {
name: 'App',
components: {
ChildComponent
},
data() {
return {
state: 0,
}
},
setup(){
setInterval(function () {
if(this.state == null){
this.state = 0
}
this.state = this.state + 1
}, 1000);
},
}
</script>
ChildComponent.vue
ChildComponent.vue
<template>
<div>
</div>
</template>
<script>
export default {
name: 'ChildComponent',
props: ["state"],
created() {
setInterval(function () {
console.log(this.state)
}.bind(this), 1000);
},
}
</script>
更多回答
优秀答案推荐
You are using this
inside setup()
, but during setup, this
is undefined. So the problem isn't in your child component, it's your interval not updating a responsive property on your parent.
您正在setUp()中使用它,但在安装过程中,它是未定义的。因此,问题不在于您的子组件,而在于您没有更新父组件上的响应属性。
Combining Options API with a setup function tends to cause these mistakes, I would suggest to either go full setup function or full Options API.
组合选项API和设置函数往往会导致这些错误,我建议使用完整的设置功能或完整的选项API。
Here is a playground using setup function
这是一个使用设置功能的游乐场
更多回答
It works. Thank you
它起作用了。谢谢
我是一名优秀的程序员,十分优秀!