Question3r
Question3r

Reputation: 3742

Component misses the first update cycle

I have a Vue app with a count up component. This component animates the change of a value by counting up from the previous value up to the new one. I forked an offical codesandbox and modified to a small sample

https://codesandbox.io/s/sweet-mclaren-j13bs 

I also created a snippet showing the code for the three components

https://pastebin.com/ki29jJpm

If you open up the codesandbox you can see that the score counter starts at 0. I would expect the code to display a 10 after 5 seconds. After that it should increase to 20 after 5 more seconds and so on...

But the actual result shows that the counter starts with 0 (which is correct), does not update after 5 seconds (which is not correct) and directly counts from 10 to 20 after 5 more seconds (which is correct). The rest of the cycles seem to work fine.

So the first update cycle was not hit. Does someone know how to fix that? After 5 seconds the number should count up from 0 to 10.

Upvotes: 0

Views: 44

Answers (1)

tony19
tony19

Reputation: 138226

You don't see the initial count up to 10 because <count-up>.update() is only invoked at created() and in a watcher on <count-up>.initialValue.

At the start, initialValue is 0 and valueToReach is 0. After 5 seconds, initialValue is 0, and valueToReach is 10. Since initialValue isn't changed, the watcher is not triggered, and update() is not called.

The solution is to add a watcher on valueToReach that also calls update():

// CountUp.vue
export default {
  watch: {
    valueToReach() {
      this.update()
    },
  },
}

demo

Upvotes: 1

Related Questions