I have a Vue2 project with a simple component displaying scores from two teams. This component is able to take the current score and the score from the last game as props (both numbers will always be positive integers). So it's easy to calculate the previous scores. Instead of displaying the current score directly I would like to add a count up animation.
This is what I have so far
<template>
<div>{{ firstTeamCounterValue }} - {{ secondTeamCounterValue }}</div>
</template>
<script>
export default {
props: {
firstTeamCurrentScore: {
type: Number,
default: 0,
},
secondTeamCurrentScore: {
type: Number,
default: 0,
},
firstTeamMapScore: {
type: Number,
default: 0,
},
secondTeamMapScore: {
type: Number,
default: 0,
},
},
data() {
return {
firstTeamCounterValue: 0,
secondTeamCounterValue: 0,
};
},
created() { // do this for the first run
this.countUpScores();
},
updated() { // do this whenever the props change (score changed)
this.countUpScores();
},
methods: {
countUpScores() {
this.firstTeamCounterValue = this.firstTeamPreviousScore;
this.secondTeamCounterValue = this.secondTeamPreviousScore;
const countUpInterval = setInterval(() => {
const firstTeamCurrentScoreReached = this.firstTeamCounterValue === this.firstTeamCurrentScore;
const secondTeamCurrentScoreReached = this.secondTeamCounterValue === this.secondTeamCurrentScore;
if (firstTeamCurrentScoreReached && secondTeamCurrentScoreReached) {
// stop
clearInterval(countUpInterval);
} else {
if (!firstTeamCurrentScoreReached) {
this.firstTeamCounterValue += 1;
}
if (!secondTeamCurrentScoreReached) {
this.secondTeamCounterValue += 1;
}
}
}, 200);
},
},
computed: {
firstTeamPreviousScore() {
return this.firstTeamCurrentScore - this.firstTeamMapScore;
},
secondTeamPreviousScore() {
return this.secondTeamCurrentScore - this.secondTeamMapScore;
},
},
};
</script>
When running the application I pass in the initial scores. Later on the props change. Unfortunately simply nothing happens. There is no count up animation.
Does someone got an idea how to make it work?
I know a little bit of CSS. If you think I shouldn't use code for this please let me know! But I don't know how I would trigger the CSS animation and pass in the required values whenever the update hook was triggered.