AlG*_*gio 5 javascript vue.js vuejs2
我正在制作一个进度条,它应该从方法submitAction接收进度状态,其中进度条的值不断更新。这是我的代码:
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>
Run Code Online (Sandbox Code Playgroud)
2. 子(进度条)组件
<template>
<div class="progress">
{{ value }}
</div>
</template>
<script>
export default {
name: 'progressbar-component',
props: {
value: {
type: Number,
default: 0
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
目的:
在运行 setInterval 时更新Progress Bar 组件中的值。
问题:
值不会在子组件中更新。
聚苯乙烯
初始代码的某些部分被省略以简化问题表示:
嗯,这花了我一些时间。经典错误。问题是你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)
}
Run Code Online (Sandbox Code Playgroud)
为了使其发挥作用,请执行以下操作:
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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1748 次 |
| 最近记录: |