0

In my vuejs-application I want to animate a number/value when it changes. The value is based on a response from the vuex-store.

so I've got the animation running, but for some reason the animation loop is infinite and just continues all the time.

data() { return { interval: false, hitsCount: 0 } }, watch: { hitsCount: function() { clearInterval(this.interval); this.interval = window.setInterval( function() { let change = this.hitsCount / 10; change = change >= 0 ? Math.ceil(change) : Math.floor(change); this.hitsCount = this.hitsCount + change; }.bind(this),20); } } 

the template is simply:

<div> {{hitsCount}} </div> 

The value hitsCount comes from a request:

this.$store.dispatch("store/data", {}).then(response => { this.hitsCount = response.total; .../ }); 

the value changes each time there is a new request.

As mentioned before, the animation starts right away and keeps counting endlessly - what am I missing here?

1
  • this happens because you're mutating a property inside its watcher, could you show where do you define the event that triggers the counter Commented Dec 17, 2020 at 9:43

2 Answers 2

1

Anyway, it's not good idea to watch property you are changing. Divide it into two variables.

data() { return { hitsCount: 0, hitsCountDisplay: 0 } }, watch: { hitsCount() { clearInterval(this.interval); if (this.hitsCount !== this.hitsCountDisplay) { let value = this.hitsCountDisplay; const change = (this.hitsCount - this.hitsCountDisplay) / 30; this.interval = setInterval(() => { value += change; this.hitsCountDisplay = Math.round(value); if (this.hitsCountDisplay === this.hitsCount) { clearInterval(this.interval); } }, 20); } } } 

and

<div> {{hitsCountDisplay}} </div> 

Here is a working example: https://jsfiddle.net/knvyrx8j/

Sign up to request clarification or add additional context in comments.

3 Comments

hmm, still the same issue: it starts counting right from the start - I only want it to count when the value changes e.g when a request is made
Than I probably understant what exactly do you want to achieve. hitsCount is your input (it can be prop or data modified inside component), could you give examples what you want to see for some changes
Changing let value = this.hitsCount; to let value = this.hitsCountDisplay; should fix the problem. I've submitted an edit.
0

You shouldn't update a property inside its watcher, this will cause an infinite loop, but you could run the animation inside the callback of your action dispatcher :

this.$store.dispatch("store/data", {}).then(response => { let count = response.total; clearInterval(this.interval); this.interval = window.setInterval( function() { let change = count / 10; change = change >= 0 ? Math.ceil(change) : Math.floor(change); this.hitsCount = this.hitsCount + change; }.bind(this),20); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.