IT이야기

구성 요소 내부에 카운트업 애니메이션을 추가하는 방법

cyworld 2022. 4. 25. 21:46
반응형

구성 요소 내부에 카운트업 애니메이션을 추가하는 방법

나는 두 팀의 점수를 보여주는 간단한 구성 요소를 가진 Vue2 프로젝트를 가지고 있다.이 구성요소는 현재 점수와 마지막 경기의 점수를 소품으로 취할 수 있다(두 수치는 항상 양의 정수임).그래서 이전의 점수를 계산하는 것은 쉽다.현재 점수를 직접 표시하는 대신 카운트업 애니메이션을 추가하고 싶다.

지금까지 내가 가지고 있는 것은 이것이다.

<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>

응용 프로그램을 실행할 때 나는 초기 점수를 통과한다.나중에 소품이 변한다.불행히도 아무 일도 일어나지 않는다.count up animation count up animation.

누가 어떻게 하면 될 지 알아냈어쩌면?

나는 CSS를 조금 안다.만약 내가 이것에 코드를 사용해서는 안 된다고 생각한다면 나에게 알려줘!하지만 업데이트 후크가 트리거될 때마다 CSS 애니메이션을 트리거하고 필요한 값을 어떻게 전달할지 모르겠다.

필요한 것은 다음과 같다.

  • A displayedCounta를 "인식"하는 데이터 속성count받침대
  • A change...하는 방법.
    • ...작거나 노쇠displayedCount의 여부에 근거하여count그 위나 아래에 있다.
    • ...재귀적으로.
    • ...할 때 자칭하지 않는다.displayedCount도달했다count
  • 에 대한 호출.change요소가 생성되는 방법
  • 에 대한 호출.change언제나count소급 업데이트

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구성 요소:2를 사용하여 2개의 점수를 추적Count내부 구성 요소이 부분은 사소한 부분이라 하게 해 주겠다;;)

소품을 관찰하고 필요한 경우에만 카운터 값을 증가시키는 지속적 간격을 가질 수 있다.

<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,
      firstValueToReach: 0,
      secondValueToReach: 0,
      countInterval: null,
    };
  },
  mounted() {
    this.firstValueToReach = this.firstTeamCurrentScore;
    this.secondValueToReach = this.secondTeamCurrentScore;
    this.countInterval = setInterval(() => {
      if (this.firstValueToReach > this.firstTeamCounterValue) {
        this.firstTeamCounterValue += 1;
      }
      if (this.secondValueToReach > this.secondTeamCounterValue) {
        this.secondTeamCounterValue += 1;
      }
    }, 50);
  },
  unmounted() {
    clearInterval(this.countInterval);
  },
  watch: {
    firstTeamCurrentScore: function (val) {
      this.firstValueToReach = val;
    },
    secondTeamCurrentScore: function (val) {
      this.secondValueToReach = val;
    },
  },
};
</script>

참조URL: https://stackoverflow.com/questions/64759539/how-to-add-a-count-up-animation-inside-a-component

반응형