Tips on utilizing setInterval in a Vue component

When defining the timer in each individual my-progress, I use it to update the value of view. However, the console shows that the value of the constant changes while the value of the view remains unchanged. How can I modify the timer to successfully change the value of view?

Vue.component('my-progress', {
    template: '\
            <div class="progress progress-bar-vertical" data-toggle="tooltip" data-placement="top">\
                <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" :style="{height: pgvalue}">{{pgvalue}}\
                </div>\
            </div>\
        ',
    data : function(){  

        return {
            pgvalue : '50%',
            intervalid1:'',
        }
    },
    computed:{

        changes : {
            get : function(){
                return this.pgvalue;
            },
            set : function(v){
                this.pgvalue =  v;
            }
        }
    },
    mounted : function(){

        this.todo()     
    },
    beforeDestroy () {

       clearInterval(this.intervalid1)
    },
    methods : {

        todo : function(){          
            this.intervalid1 = setInterval(function(){
                this.changes = ((Math.random() * 100).toFixed(2))+'%';
                console.log (this.changes);
            }, 3000);
        }
    },
})

For additional reference, please visit: jsbin.com/safolom

Answer №1

this isn't referencing the Vue object. Give this a try:

todo: function(){           
    this.intervalid1 = setInterval(function(){
        this.changes = ((Math.random() * 100).toFixed(2))+'%';
        console.log (this.changes);
    }.bind(this), 3000);
}

or

todo: function(){  
    const self = this;          
    this.intervalid1 = setInterval(function(){
        self.changes = ((Math.random() * 100).toFixed(2))+'%';
        console.log (this.changes);
    }, 3000);
}

or

todo: function(){  
    this.intervalid1 = setInterval(() => {
        this.changes = ((Math.random() * 100).toFixed(2))+'%';
        console.log (this.changes);
    }, 3000);
}

Check out How to access the correct this inside a callback?

Answer №2

take a look at this demo:

Vue.component('my-progress-bar',{
template:
`<div class="progress">
<div
class="progress-bar"
role="progressbar"
:style="'width: ' + percent+'%;'"
:aria-valuenow="percent"
aria-valuemin="0"
aria-valuemax="100">
{{ percent }}%
</div>
</div>`,
props: { percent: {default: 0} }
});


new Vue({
el: '#app',
data: {p: 50},
created: function() {
var self = this;
setInterval(function() {
        if (self.p<100) {
             self.p++;
         }
    }, 100);
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet>

<div id='app'>
  <my-progress-bar :percent.sync='p'>
  </my-progress-bar>
  <hr>
  <button @click='p=0' class='btn btn-danger bt-lg btn-block'>
  Reset Bar Progress
  </button>
</div>

Answer №3

created : {

  window.setInterval(() => {
    getList(); // initiate any function or endpoint
  }, 1000); // set interval to one second

}


const getList = () => {
    console.log('bar')
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

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

Troubleshooting JavaScript Integration in PHP Scripts

I'm currently working on creating an advertisement switcher that can display different ads based on whether the user is on mobile or desktop. I've tried inserting PHP includes directly into the code, and while it works fine, I'm struggling t ...

What is the process for altering a variable within an Ajax function?

Scenario: I'm dealing with JSON data fetched from the backend which needs to be presented in a table format. To achieve this, I've created a string called tableOutputString and am populating it by iterating through the JSON response. Finally, I&a ...

Can you nest an if statement within another if statement within a return statement?

Is it feasible to include an if statement inside another if statement within a return function? I understand the standard syntax like: return ( <div> { myVar ? <Component/> : <AnotherComponent/> } </div> ...

Improving a lengthy TypeScript function through refactoring

Currently, I have this function that I am refactoring with the goal of making it more concise. For instance, by using a generic function. setSelectedSearchOptions(optionLabel: string) { //this.filterSection.reset(); this.selectedOption = optionLa ...

What is the process for creating a React Component with partially applied props?

I am struggling with a function that takes a React component and partially applies its props. This approach is commonly used to provide components with themes from consumers. Essentially, it transforms <FancyComponent theme="black" text="blah"/> int ...

Employing ajax with dynamically created buttons in PHP

I'm struggling to figure out what to search for in this situation. I've tried piecing together code from others, but it's just not working for me. My ajax function successfully retrieves data from a database through a php page and displays ...

The function window.addEventListener('load') functions properly on desktop computers, but does not work on mobile devices

After developing a react website, I noticed that it functions correctly on PC but not on Mobile devices. componentDidMount() { window.addEventListener('scroll', this.onScroll); // This event works fine window.addEventListener('load&a ...

Create a unique bar chart plugin using Javascript/jQuery that allows users to drag and drop data

My current project involves developing a custom bar chart generator that must meet specific criteria: Input fields for entering data to display on the chart The ability to drag and resize bars once the chart is generated I've conducted research and ...

The system has encountered an issue: "EntityMetadataNotFound: Unable to locate metadata for the entity named 'User

Just wanted to reach out as I've been encountering an issue with my ExpressJS app recently. A few days ago, everything was running smoothly without any errors. However, now I'm getting a frustrating EntityMetadataNotFound: No metadata for "User" ...

The React app I've been working on has a tendency to unexpectedly crash when reloading the code from time

Dealing with a frustrating issue here. I've been working on an app and for the past few weeks, it keeps crashing unexpectedly. It seems to happen more frequently after saving my code to trigger a reload, but it can also just crash randomly while navig ...

What is the best way to manage div visibility and sorting based on selections made in a select box?

Explaining this might get a bit confusing, but I'll do my best. In my setup, I have two select boxes and multiple divs with two classes each. Here is what I am trying to achieve: When an option is selected, only the divs with that class should be ...

Node.js & Express: Bizarre file routes

It's quite strange how my local paths are functioning. Let me show you an example of my directory structure: public > css > bootstrap.css public > js > bootstrap.js templates > layout > page.ejs (default template for any page) tem ...

Obtain the file path relative to the project directory from a Typescript module that has been compiled to JavaScript

My directory structure is as follows: - project |- build |- src |- index.ts |- file.txt The typescript code is compiled to the build directory and executed from there. I am seeking a dependable method to access file.txt from the compiled module without ...

Duplicate entries in the angular-ui Calendar

I've implemented the Angular-UI calendar to showcase some events. My activity controller interacts with the backend service to fetch the data, which is then bound to the model. //activity controller $scope.events = []; Activities.get() ...

Is there a way to eliminate currency within an Angularjs directive?

Currently, I am utilizing a directive to properly display currency format. You can find the directive at this URL: http://jsfiddle.net/ExpertSystem/xKrYp/ Is there a way to remove the dollar symbol from the output value and only retain the converted amoun ...

connect a column from a separate array in pdfmake

In my current project, I am looking to link the values of an array that is different from the one present in the initial two columns. Is this achievable? (The number of partialPrice values aligns with the number of code entries). Despite several attempts ...

Verifying the timestamp of file submission in a form

My goal is to create an HTML form that allows users to send a file to my server, while also recording the exact time they initiated the file transfer. However, I'm facing an issue where only the time the file is received is being logged, rather than w ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

Struggling to access YouTube account via Google sign-in using Puppeteer framework

I am facing an issue with my puppeteer code where I am unable to proceed past the email page after clicking next due to some bot protection by Google advising me to "Try using a different browser...etc". Is there a way to bypass this using puppeteer? I h ...

Converting form data into an object using JavaScript (Encountering an error: Cannot access property 'name' of undefined)

I recently started learning about MongoDB and I am following this tutorial here. The tutorial shows how to create a submit form that adds a person's name, age, and nationality to the database. However, I encountered the following error: TypeError: Can ...