我有一个 Vue2 元素,其中有一个简单的组件显示两个团队的分数。该组件能够将当前分数和上一场比赛的分数作为 Prop (这两个数字始终为正整数)。所以很容易计算以前的分数。我想添加一个计数动画,而不是直接显示当前分数。
这是我到目前为止
<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>
运行应用程序时,我传递了初始分数。后来 Prop 变了。不幸的是,什么也没有发生。没有计数动画。有人知道如何使它工作吗?
我知道一点CSS。如果您认为我不应该为此使用代码,请告诉我!但是我不知道如何触发 CSS 动画并在触发更新 Hook 时传入所需的值。
最佳答案
这是您需要的:
displayedCount
“跟随”一个 count
的数据属性 Prop change
方法...displayedCount
基于是否count
高于或低于它 displayedCount
时不调用自身已到达 count
change
创建元素时的方法 change
方法每当 count
Prop 更新您可能会找到使用 setInterval 使其工作的方法,但我发现递归 setTimeout 在这里更好。
这是一些工作代码。更新输入中的数值,观察
Count
显示的数值制作一个倒数动画:Vue.config.productionTip = false;
const Counter = {
template: `<span>{{ displayedCount }}</span>`,
props: ['count'],
data() {
return {
displayedCount: 0
}
},
created() {
this.change();
},
watch: {
count() {
this.change();
}
},
methods: {
change() {
if (this.displayedCount === this.count) return;
if (this.displayedCount < this.count) this.displayedCount++;
if (this.displayedCount > this.count) this.displayedCount--;
setTimeout(() => this.change(), 200);
}
}
};
const App = new Vue({
el: '#app',
components: { Counter },
template: `
<div>
<input type="number" v-model="count">
<Counter :count="count"/>
</div>
`,
data() {
return {
count: 0
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
您在问题中要求让一个组件跟踪两个分数。我觉得拥有一个更优雅
Count
组件跟踪一个分数,可能还有另一个 Counts
组件使用两个 Count
跟踪两个分数内部组件。这部分是微不足道的,所以我会让你做;)
关于javascript - 如何在组件内添加计数动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64759539/