본문 바로가기
FrontEnd/others

[ Vue ] computed vs watch (feat. method )

by ウリ김영은 2024. 3. 14.

Nuxt(Vue)로 만들어진 프로젝트를 React로 마이그레이션을 하게 됐습니다.

러닝커브가 React 보다 낮다고 들었던 Vue, 전 헷갈리는 개념들이 너무 많더라구요.

그 중 하나가 바로 이 둘입니다.

computed 와 watch, 둘 다 값이 바뀌면 실행되는 함수들인데,

무슨 차이가 있어서 이렇게 구분되어 있는 것일까요.
(공식문서에도 둘을 비교하는 페이지가 있습니다.

https://v2.vuejs.org/v2/guide/computed#Computed-vs-Watched-Property )

computed

일단, computed 가 무엇일까요?

 

빠른 이해를 위해 공식문서의 예제를 가져왔습니다.
(저는 (vue v2의 공식문서)[https://v2.vuejs.org/]를 보고 있습니다.)

 

<div id="example">
  {{ message.split('').reverse().join('') }}
</div>

 

공식문서에서 이 코드는 간단하고 직관적이지 못하다고 하고 있습니다.

 

특히, 로직이 더 복잡해지고,
반복적으로 사용해야 하는 경우에는 더 별로겠죠?

 

그래서 computed를 사용하라고 합니다.

 

//html
<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>

//js
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    reversedMessage: function () {
      return this.message.split('').reverse().join('')  // `this` points to the vm instance
    }
  }
})

 

그렇다면 여기서 다시 하나의 궁금증이 생깁니다.

 

"method와는 뭐가 다른걸까?"

둘 다 함수의 리턴값을 받는 것인데, 어떻게 다를까요?

computed vs method

이 부분에 대해서도 공식문서에서는 설명하고 있습니다.

Instead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed. This means as long as message has not changed, multiple access to the reversedMessage computed property will immediately return the previously computed result without having to run the function again.

 

요약하자면,


computed 대신 method 를 사용할 수도 있습니다. 
하지만, computed는 캐싱의 기능이 있어서 이전의 값이 바뀌어야 실행이 됩니다.
method는 값의 변경 유무와 상관없이 재랜더링 때마다 재실행됩니다.

 

그렇기 때문에, 

reactive한 값에 대해서는 computed를 쓰는 게 더 좋겠습니다.

watch

말 그대로 특정 대상을 보고 있는 감시자 역할을 하는데,
지정한 대상의 값이 변경될 때마다 정의한 함수가 실행됩니다.

 

기존의 vue 인스턴스의 값을 감시하는 것이기 때문에,
이미 인스턴스 내에서 선언된 값들 만 사용 가능합니다.

 

computed와 비교해서 설명해보자면,

  • computed는 이미 정의된 계산식에 따라 결과값을 반환할 때 사용한다면,
  • watch는 어떤 특정 조건에서 함수를 실행시키기 위한 트리거로 사용합니다.
In this case, using the watch option allows us to perform an asynchronous operation (accessing an API), limit how  
often we perform that operation, and set intermediary states until we get a final answer. None of that would be possible with a computed property.

 

대부분의 상황에서는 computed를 사용하지만,
변한 값에 따라 비동기적인 처리를 해야하는 경우에는 watch를 사용합니다.

 

 

그리고 $vm.watch API도 사용이 가능하다고 하네요.