[英]Vue.js. Passing dynamically changing data to child component
I'm making a progress bar, which should receive progress status from method submitAction , in which value for progress bar constantly updating. 我正在创建一个进度条,它应该从方法submitAction接收进度状态,其中进度条的值不断更新。 Here my code: 这是我的代码:
1.Parent component 1.Parent组件
<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. Child (progress bar) component 2.子(进度条)组件
<template>
<div class="progress">
{{ value }}
</div>
</template>
<script>
export default {
name: 'progressbar-component',
props: {
value: {
type: Number,
default: 0
}
}
}
</script>
Aim: 目标:
Updating value in Progress Bar's component, while setInterval is running. 在setInterval运行时更新Progress Bar组件中的值 。
Problem: 问题:
value doesn't update in child component. 值不会在子组件中更新。
PS PS
Some parts of initial code are just left out to simplify problem representation: 初始代码的某些部分被省略以简化问题表示:
Well, this took me some time. 嗯,这花了我一些时间。 Classic mistake. 经典错误。 The problem is you don't really change components' progress
ever: 问题是你并没有真正改变组件的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)
}
to make it work do: 让它工作做:
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.