[Vue3] computed와 watch 옵션

Dohee Kang·2023년 3월 4일
1

Vue

목록 보기
13/28

1. Computed

  • 템플릿 안에서 연산을 하게 되면 가독성이 떨어지고 유지보수가 어려워진다.
  • 템플릿에서 사용할만한 로직은 일반적으로 computed에서 사용한다.
  • computed는 default로 getter() 함수가 있지만 필요에 의해 setter() 함수를 설정할 수 있다.
<template>
  <p>원본 배열 : {{ arr }}</p>
  <p>역순 배열 : {{ reverseArr }}</p>
</template>

<script>
export default {
  data() {
    return {
      arr: [1, 2, 3, 4, 5]
    }
  },
  computed: {
    // getter
    reverseArr: function () {
      return [...this.arr].reverse()
    }
  }
}
</script>

🧐 computed와 methods 사용하는 방법이 같은데 차이점이 뭘까?

  • computed
    • 종속 대상을 캐싱한다. 그래서 종속 대상이 변경될 때만 함수를 호출한다.
      • e.g. reverseArr의 종속 대상은 arr
    • arr의 값이 바뀌지 않는다면 reverseArr를 여러번 호출해도 다시 계산하지 않고 캐싱한 결과를 즉시 반환한다.
  • methods
    • 호출할 때마다 새롭게 계산해야 하는 경우 methods를 사용한다.

2. Watch

  • 대부분 computed 속성이 적합하지만 사용자가 특정 지정한 값을 감시하는 경우 watch 옵션을 사용한다.
  • 상태 변경에 대한 반응으로 수행해야 할 때 watch 옵션을 사용하여 상태 변경이 발생할 때 함수를 실행할 수 있다.
  • 옵션 API만 가능하다.
<template>
  <p v-if="isShow">질문에는 일반적으로 물음표가 포함됩니다.</p>
  <span>질문 : </span>
  <input :value="question" @input="questionInput" />
  <p> answer : {{ answer }}</p>
</template>

<script>
export default {
  data() {
    return {
      question: '',
      answer: '',
      isShow: true
    }
  },
  watch: {
    question(newQuestion) {
      if (newQuestion) this.isShow = false;
      else this.isShow = true;

      if (newQuestion.indexOf('?') > -1) this.getAnswer()
    }
  },
  methods: {
    questionInput(event) {
      this.question = event.target.value;
    },
    async getAnswer() {
      this.answer = '생각 중...'
      try {
        const res = await fetch('https://yesno.wtf/api');
        this.answer = (await res.json()).answer === 'yes' ? '네' : '아니오'
      } catch (error) {
        this.answer = `Error : ${error}`;
      }
    }
  }
}
</script>

🧐 computed vs watch

  • 대부분의 경우 computed를 사용하는 것이 적절하지만 watch를 사용해야 할 경우가 있다.
    • 데이터를 업데이트할 때 비동기 처리 혹은 많은 로직을 실행할 때
    • computed는 선언형이고 , watch는 명령형이다.
      • 선언형 프로그래밍 : 계산해야 하는 목표 데이터를 정의하는 방식
      • 명령형 프로그래밍 : 감시할 데이터를 지정하고 그 데이터가 바뀌면 선언한 함수를 실행하라는 방식
  • watchcomputed 비교
// watch
data() {
  return {
    firstName: 'Dohee',
    lastName: 'Kang',
    fullName: 'Dohee Kang'
  }
},
watch: {
  // firstName이 바뀔 경우
  firstName: function (value) {
    this.fullName = `${value} ${this.lastName}`;
  },
  // lastName이 바뀔 경우
  lastName: function (value) {
    this.fullName = `${this.firstName} ${value}`;
  }
}

// computed
data() {
  return {
    firstName: 'Dohee',
    lastName: 'Kang'
  }
},
computed: {
  fullName: function () {
    return `${this.firstName} ${this.lastName}`;
  }
}
profile
오늘은 나에게 어떤 일이 생길까 ✨

0개의 댓글