Mi Lugarcito

Vue.js - Computed & Watch 차이점 본문

Vue & Nuxt.js

Vue.js - Computed & Watch 차이점

selene park 2022. 5. 13. 09:19

Computed 예시

참조하고 있는 값이 변경될때마다 정의한 계산식에 따라 값을 출력함

<div class="common_pagination font_youandi" v-if="!!user_data.product_list.length">
  <button :class="{'common_pagination_disabled' : pageNum === 0}" :disabled="pageNum === 0" @click="prevPage">이전</button>
  <span>{{ pageNum + 1 }} / {{ pageCount || 0 }}</span>
  <button :class="{'common_pagination_disabled' : pageNum + 1 === pageCount}" :disabled="pageNum + 1 === pageCount" @click="nextPage">다음</button>
</div>


computed:{
	pageCount () {
        let listLeng = this.user_data.product_list.length,
          listSize = this.pageSize,
          page = Math.floor(listLeng / listSize);

        if (listLeng % listSize > 0) {
          page += 1;
          return page;
        }
    },
}

 

Watch 예시

지정한 대상의 값이 변경될때마다 정의한 함수가 실행된다.

data(){
	return{
    	modal_state: { // 모달 상태
          point: false,
          point_history: false,
          info: false,
          coupon: false,
          coupon_add: false,
          message: false,
          product_add: false,
          add_complete: false
        },
    }
}


watch: {
  // 포인트 사용/추가 모달 타입 초기화
  'modal_state.point'(val) {
    if(!val) this.total_data.point.point_type = 'use'
  },
  // 메세지 보내기 모달 타입 초기화
  'modal_state.message'(val) {
    if(!val) this.total_data.message.message_type = 'SMS'
  }
},