我正在创建一个进度条,它应该从方法 submitAction 接收进度状态,其中 value 用于进度条不断更新。这是我的代码:
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。子(进度条)组件
<template>
<div class="progress">
{{ value }}
</div>
</template>
<script>
export default {
name: 'progressbar-component',
props: {
value: {
type: Number,
default: 0
}
}
}
</script>
目的:
在setInterval正在运行时,在Progress Bar的组件中更新值。
问题:
子组件中value 不会更新。
P.S。
初始代码的某些部分被省略以简化问题表示:
答案 0 :(得分:2)
嗯,这花了我一些时间。经典错误。问题是你并没有真正改变组件&#39;永远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)
}