본문 바로가기

Vue/vue 기초 공부하기

반응속도 측정 게임 만들기(v-if, v-show, computed 활용)

반응형

https://github.com/loy124/Vue/tree/master/반응속도체크

 

loy124/Vue

Vue 공부. Contribute to loy124/Vue development by creating an account on GitHub.

github.com

 

computed를 사용하는 이유 : data에 있는 간단한 데이터를 가공해서 사용할때

computed를 활용한다.( 값이 캐싱이되서 사용한다, 새로 불러낼 필요없이 캐싱된 average를 활용해서 시간 단축에 도움이 된다. 즉 성능 최적화)

 

v-show :
false 일경우 display none 
true 일경우 display 된다

 

레이아웃 구성을 할때 생각을 하고 사용하면 된다

 

v-if인 경우는 아에 태그 자체가 존재하지 않게된다

v-show인 경우 display : none

v-if를 조금더 많이 사용한다 

 

 

<template>
  <div>
    <!-- state가 waiting을 가리킨다  v-bind:class class에 state를 가리킨다. -->
    <!-- <div id="screen" v-bind:class="state">{{}}</div> -->
    <!-- 축약형 -->
    <div id="screen" :class="state" @click="onClickScreen">{{ message }}</div>
    <!-- 단순 감싸는 용도일 경우 div 대신 template(없는 태그로 친다)-->
    <!-- <template v-if="result.length"> -->
    <template v-show="result.length">
      <div>
        평균 시간 :
        {{ average }} ms
      </div>
      <button @click="onReset">리셋</button>
    </template>
  </div>
</template>

<script>
let startTime = 0;
let endTime = 0;
let timeout = null;
export default {
  data() {
    return {
      result: [],
      state: 'waiting',
      message: '클릭해서 시작하세요',
    };
  },
  // computed는 값이 캐싱되기때문에 새로 호출할 필요없이 그전에 캐싱되어있는 값을 호출하기때문에 사용한다.(웹의 불필요한 시간 단축)
  // 성능 최적화
  computed: {
    average() {
      //값을 더해서 누적시킨후 해당 값을 배열의 길이만큼 나누어 평균값을 도출하는 함수
      return this.result.reduce((a, c) => a + c, 0) / this.result.length || 0;
    },
  },
  methods: {
    onReset() {
      this.result = [];
    },
    onClickScreen() {
      if (this.state === 'waiting') {
        this.state = 'ready';
        this.message = '초록색이 되면 클릭하세요';
        timeout = setTimeout(() => {
          this.state = 'now';
          this.message = '지금 클릭!!!';
          startTime = new Date();
        }, Math.floor(Math.random() * 1000) + 2000); //2~3초
      } else if (this.state === 'ready') {
        //너무 성급한 경우
        clearTimeout(timeout);
        this.state = 'waiting';
        this.message = '너무 성급하시군요! 초록색이 되면 클릭하세요!';
      } else if (this.state === 'now') {
        endTime = new Date();
        this.state = 'waiting';
        this.message = '클릭해서 시작하세요';
        this.result.push(endTime - startTime);
      }
    },
  },
};
</script>

<style scoped>
/* scoped 를 사용하면 해당 컴포넌트 안에서만 유효한 css가 적용된다 */
#screen {
  width: 300px;
  height: 200px;
  text-align: center;
  user-select: none;
}
#screen.waiting {
  background-color: aqua;
}
#screen.ready {
  background-color: red;
  color: white;
}
#screen.now {
  background-color: greenyellow;
}
</style>

 

반응형