newbiedev
newbiedev

Reputation: 3586

Vue - set bootstrap 5 progress bar width according to countdown timer advance

I want to use a bootstrap 5 progress bar to show the remaning time of a countdown. I've created the needed markup in my vuejs component template

          <div class="progress">
            <div class="progress-bar" ref="elaspedTime" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
              {{ minutes }} seconds
            </div>
          </div>

In my methods I have this two functions, one is for starting the countdown and the other to stop it when the minutes reach the zero.

    startTimer(){
      this.$refs.elaspedTime.width = '0%';
      this.countdown = setInterval( () => {
        this.minutes--;
        if( this.$refs.elaspedTime.width < '100%' ){
          this.$refs.elaspedTime.width += '0.6%';
        }
        if( this.minutes === 0 ){
          this.stopTimer();
        }
      },1000);
    },
    stopTimer(){
      clearInterval(this.countdown);
    }

How I can change the progress bar width until it reach the 100% according to the countdown minutes elasped?

Upvotes: 0

Views: 1792

Answers (1)

Carol Skelly
Carol Skelly

Reputation: 362390

You can do something like this...

new Vue({
    el: "#app",
    data: () => ({
        minutes: 10,
        countdown: null
    }),
    methods: {
        startTimer(){
          let seconds = this.minutes // initial time
          let et = this.$refs.elaspedTime
          et.style.width = '0%'
          this.countdown = setInterval(() => {
            this.minutes--;
            et.style.width = ((seconds - this.minutes) * 100)/seconds + '%'
            if(this.minutes === 0){
              this.stopTimer();
            }
          },1000);
        },
        stopTimer(){
          clearInterval(this.countdown);
        }
    },
})

Demo


Also see: Using Bootstrap 5 with Vue

Upvotes: 2

Related Questions