Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Here my code:

1.Parent component

<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

<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.

Problem:

value doesn't update in child component.

P.S.

Some parts of initial code are just left out to simplify problem representation:

  • this.progress value changes correctly in parent, and I can track it
  • through debugger progress bar component also works correctly and initial value of progress (i.e. 0) passed fine.
like image 361
AlGiorgio Avatar asked Oct 17 '22 20:10

AlGiorgio


1 Answers

Well, this took me some time. Classic mistake. The problem is you don't really change components' progress ever:

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)
}
like image 75
oniondomes Avatar answered Oct 19 '22 23:10

oniondomes