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

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 组件中的

问题:

不会在子组件中更新。

聚苯乙烯

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

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

oni*_*mes 3

嗯,这花了我一些时间。经典错误。问题是你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)