gpt4 book ai didi

javascript - Vue.js。将动态变化的数据传递给子组件

转载 作者:搜寻专家 更新时间:2023-10-30 22:25:07 27 4
gpt4 key购买 nike

我正在制作一个进度条,它应该从方法 submitAction 接收进度状态,其中进度条的 value 不断更新。这是我的代码:

1.父组件

<template>
<div>
<progressbar-component :value="progressState"></progressbar-component>
</div>
</template>
<script>
import ProgressBar from './Progress.vue'
export default {
components: {
'progressbar-component': ProgressBar
},
data () {
return {
...
progress: 0
...
}
},
computed: {
...
progressState () {
return this.progress
}
...
},
methods: {
...
submitAction: function (event) {
...
let percent = 0
setInterval(function () {
if(someState > 0) {
this.progress = percent % 100
percent += 10
}
}, 200)
...
}
}
}
</script>

<强>2。子(进度条)组件

<template>
<div class="progress">
{{ value }}
</div>
</template>
<script>
export default {
name: 'progressbar-component',
props: {
value: {
type: Number,
default: 0
}
}
}
</script>

目标:

在运行 setInterval 时更新进度条组件中的

问题:

不会在子组件中更新。

附言

初始代码的某些部分被省略以简化问题表示:

  • this.progress 值在父级中正确更改,我可以跟踪它
  • 通过调试器进度条组件也能正常工作并且progress 的初始值(即 0)顺利通过。

最佳答案

好吧,这花了我一些时间。经典错误。问题是你并没有真正改变组件的 progress :

submitAction: function (event) {        
let percent = 0
setInterval(function () {
if(someState > 0) {
this.progress = percent % 100 // <---- `this` here doesn't refer to the component
percent += 10
}
}, 200)
}

让它工作:

submitAction: function (event) {        
let percent = 0
setInterval(() => { // <---- arrow function doesn't have their own `this`, so `this.progress` will refer to the components' value
if(someState > 0) {
this.progress = percent % 100
percent += 10
}
}, 200)
}

关于javascript - Vue.js。将动态变化的数据传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49688115/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com