Dynamically sending data to child components in Vue.js

I'm currently working on a progress bar implementation where the progress status is determined by the submitAction method. The value for the progress bar is constantly being updated in this method. Here's my code:

1. Parent Component

<template>
    <div>
        <progressbar-component :value="progressState" />
    </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(() => {
                    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:

The goal is to update the value in the Progress Bar component while the setInterval function is running.

Problem:

The value does not update in the child component.

P.S.

Some parts of the original code have been omitted for simplicity:

  • The parent component's progress value changes correctly, and can be tracked.
  • By debugging, it is evident that the progress bar component functions properly, and the initial value of progress (which is 0) is passed successfully.

Answer №1

After spending some time on this issue, I realized a common mistake being made. The problem lies in the fact that components' progress is not being updated:

submitAction: function (event) {        
    let percent = 0
    setInterval(function () {
        if(someState > 0) {
            this.progress = percent % 100    // <---- In this context, `this` does not refer to the component
            percent += 10
        }
    }, 200)
}

To resolve this issue, make the following changes:

submitAction: function (event) {        
    let percent = 0
    setInterval(() => {    // <---- Arrow functions retain the parent's `this`, allowing for correct reference to the components' value
        if(someState > 0) {
            this.progress = percent % 100 
            percent += 10
        }
    }, 200)
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React - method for transmitting dynamically generated styles to a div element

As a newcomer to the world of React, I keep encountering an unexpected token error related to the ":". Can someone please assist me with understanding the correct syntax for including multiple styles within the Box component provided below? Additionally, h ...

What is the best way to access the req.user variable from Passport in client-side JavaScript?

I have successfully implemented Passport authentication in my Express application and everything is working perfectly. On my index page, I am displaying req.user as follows: <% if (!isAuthenticated) { %> <a id="signIn" href="/login">Sign I ...

Adjusting the dimensions of the central container

Does anyone have suggestions on how to resize the middle red container when the window is resized, considering the fixed-width black containers on the left and right? I am aware that this can be achieved using jQuery by calculating the window width and a ...

When I expand the accordion next to it, the accordion disappears, and it also vanishes when I close that accordion

After incorporating accordions into my site, I encountered a peculiar issue (as shown in this video): when I open one accordion, the adjacent accordion also opens unexpectedly. Similarly, closing one accordion causes its neighboring accordion to mysterious ...

Troubleshooting the Issue of Table Append not Functioning in Live Environment

I'm currently in the process of developing a website using Bootstrap, and I'm facing an issue where one of the tables gets cleared out and updated with new data when a button is clicked. This functionality works perfectly fine during testing on V ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

What is the significance of this hint regarding the Vue devtools version?

While checking my Vue devtools, I noticed a version hint displayed: I am confused about the origin of the version number 3.2.28 mentioned in the hint. My current Vue version is actually 3.2.25. ...

What is the best way to save a scheduled cron reference in a database in order to deactivate it at a later time in a

I have implemented a system using cron to schedule push notifications. The user provides the push notification data and the scheduled time, and I use cron to send the notifications at the specified time. Below is the code snippet showing how I create a cr ...

Tips for making sure AngularJS runs a function and its subfunction sequentially

How do I run the code below to display the details of each flavor and its corresponding ITEM ID in a specific order. Execution Format: Flavor1, Flavor2 -- Getflavors() Flavor1 ITEM1, ITEM2... -- GetItemIDs_ofeachFlavor(MapFlvID) GET ITEM1 DETAILS and ad ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

Troubleshooting issue: Unable to refresh and generate a valid access token using axios in a Vue.js

Initially, I set the default Authorization header for axios requests in axios.js. It worked fine at first, but whenever I refresh the page, it shows a 500 internal server error. Here is how I defined it in axios.js: // axios import axios from 'axios& ...

Problem occurs when tab links vanish after clicking on another part of the website

Exploring the world of Javascript as a newcomer has been quite an adventure, but I've encountered a hurdle with tab links on my website. Everything seems to be working fine – the links cycle through and display the correct content. However, when it ...

Animating content through CSS and jQuery to reveal its unfolding effect

Just stumbled upon the amazing quote-expansion animation in the OSX Mail app and I am completely impressed. I am on a mission to bring that same magic to the web (or at least close to it), but unsure if anyone has done something similar yet. A couple of ...

Exploring the world of JSON manipulation in JavaScript

I've been experimenting with JSON recently and came across something I don't quite understand. Here is an example of some code I used: var str = "{'name':'vvv'}"; var cjson = eval ("(" + str + ")"); alert( ...

Having trouble reaching the elements stored in an array?

As a beginner in Angular and JavaScript, I may be making some obvious mistakes so please bear with me. I have written this code that allows the selection of 2 text files and then combines them into a single array. $scope.textArray = []; $scope.textUpload ...

Trouble accessing setState within an axios call in ReactJs

I've encountered an issue while attempting to set the state of the variable isCorrectAnswer within an axios call. The error message Cannot read properties of undefined (reading 'setState') is showing up in the console log. What mistake am I ...

Switch up the text within the URL of the background image

Simply put, this is the structure I have: <div id="RelatedPosts1"> <div class="related-posts-thumb" style="background: url(http://xxxxxxx/s72-c/image-1.jpg)"></div> <div class="related-posts-thumb" style="background: url(http: ...

Issue with React component not updating content after state changes in Next.js framework

Currently, I am facing an issue with my Header component not updating its content on state change. The goal is to show the user's Profile once the state changes, but unfortunately, it does not update immediately; it only changes after a page refresh o ...

Skipping validation while navigating back on SmartWizardIf you need to bypass validation during backward

Looking for assistance with Jquery smartwizard? Check out the link. I want to disable validation when a user clicks on the "Previous" button in any step, except for the first step where the Previous button is disabled by default. Below is my JavaScript co ...

Failed Azure Pipeline due to the absence of the vueapp.key file during the npm run build process

I'm encountering issues while trying to build a Vue app in Azure pipelines. I lack experience with NodeJS and Vue, so I'm unsure about what it requires. My application builds and runs smoothly locally. Any guidance would be highly appreciated. I ...