🤔회사에서 Vue 개발을 하면서 computed를 사용하는 경우가 종종 있어 computed 에 대해 알아보려 한다.

 (학습을 위한 정리로 틀린 정보가 있다면 말씀 주시면 감사하겠습니다.)

 

Computed 사용 및 함수와 차이점

<template> 내 삼항 연산자처리

<template>
  <div>
    <h2>책 제목이 5글자 이상인 경우인가요?</h2>
    <h3>{{ book.title.length > 5 ? '예' : '아니오' }}</h3>
  </div>
</template>

<script>
import { reactive } from 'vue'
export default {
  setup() {
    const book = reactive({
      title: 'vue 학습 책입니다.',
      author: 'test'
    })
    return {
      book
    }
  }
}
</script>

 

위 코드를 보면 ‘책 제목이 5글자 이상’인 경우를 <template> 안에서 삼항 연산자를 통해 체크하여 ‘예’ / ‘아니오’ 로 출력해주고 있다. 하지만, 이와 같은 코드는 가독성이 떨어지기 때문에 computed 또는 함수를 사용하여 기능을 처리하는 것이 효율적인 코드이다.

 

computed 사용

<template>
  <div>
    <h2>책 제목이 5글자 이상인 경우인가요?</h2>
    <h3>{{ checkBookTitle}}</h3>
  </div>
</template>

<script>
import { computed, reactive } from 'vue'
export default {
  setup() {
    const book = reactive({
      title: 'vue 학습 책입니다.',
      author: 'test'
    })

    const checkBookTitle= computed(() => {
      return book.title.length > 5 ? '예' : '아니오'
    })

    return {
      book,
      checkBookTitle
    }
  }
}
</script>

 

method 사용

<template>
  <div>
    <h2>책 제목이 5글자 이상인 경우인가요?</h2>
    <h3>{{ checkBookTitle }}</h3>
    <h3>{{ methodBookTitle() }}</h3>
  </div>
</template>

<script>
import { computed, reactive } from 'vue'
export default {
  setup() {
    const book = reactive({
      title: 'vue 학습 책입니다.',
      author: 'test'
    })

    const checkBookTitle = computed(() => {
      return book.title.length > 5 ? '예' : '아니오'
    })

    const methodBookTitle = () => {
      return book.title.length > 5 ? '예' : '아니오'
    }

    return {
      book,
      checkBookTitle,
      methodBookTitle
    }
  }
}
</script>

 

위 코드와 같이 methodBookTitle() 함수와, checkBookTitle computed를 사용하여 함수명을 통해 어떤 것을 출력하고 싶은지 예측도 가능하게 된다.

함수와, computed 호출 결과 두 코드는 모두 ‘예’ 로 같은 결과를 보여준다.

그렇다면, 함수와 computed의 차이점을 확인해보면 computed는 cache 기능을 갖고 있다

 

<template>
  <div>
    <h2>책 제목이 5글자 이상인 경우인가요?</h2>
    <h3>{{ checkBookTitle }}</h3>
    <h3>{{ checkBookTitle }}</h3>
    <h3>{{ methodBookTitle() }}</h3>
    <h3>{{ methodBookTitle() }}</h3>
  </div>
</template>

<script>
import { computed, reactive } from 'vue'
export default {
  setup() {
    const book = reactive({
      title: 'vue 학습 책입니다.',
      author: 'test'
    })

    const checkBookTitle = computed(() => {
      console.log('computed')
      return book.title.length > 5 ? '예' : '아니오'
    })

    const methodBookTitle = () => {
      console.log('methods')
      return book.title.length > 5 ? '예' : '아니오'
    }

    return {
      book,
      checkBookTitle,
      methodBookTitle
    }
  }
}
</script>

 

위 코드에서 computed인 checkBookTitle 와 함수인 methodsBookTitle() 을 각각 2번씩 호출한 결과

console.log 가 어떻게 찍히는지 확인해보면, ‘computed’ 는 한 번 그리고 methods는 두번 출력된 것을 볼 수 있다.

computed는 내부 데이터 값이 변경되지 않을 경우 cache된 데이터를 가져온다.

Computed get, set

computed의 경우 기본적으로 readonly 속성을 갖고 있어 새로운 값을 할당하려 하면 readonly warning이 뜬다. 이를 해결하기 위해 getter, setter 를 같이 활용해서 사용한다.

아래 소스는 readonly인 computed 값을 변경하려 할때 나오는 warning 예제와 이를 해결하기 위해 사용된 getter / setter 코드이다.

 

<template>
  <div>
    <h2>책 제목이 5글자 이상인 경우인가요?</h2>
    <h3>{{ checkBookTitle }}</h3>
    <h3>{{ checkBookTitle }}</h3>
    <h3>{{ methodBookTitle() }}</h3>
    <h3>{{ methodBookTitle() }}</h3>
    <h2>author</h2>
    <h3>{{ authorName }}</h3>
  </div>
</template>

<script>
import { computed, reactive, ref } from 'vue'
export default {
  setup() {
    const book = reactive({
      title: 'vue 학습 책입니다.',
      author: 'test'
    })

    const checkBookTitle = computed(() => {
      console.log('computed')
      return book.title.length > 5 ? '예' : '아니오'
    })

    const methodBookTitle = () => {
      console.log('methods')
      return book.title.length > 5 ? '예' : '아니오'
    }

    const authorName = ref('락토')
    const changeName = computed(() => authorName.value + '핏')

    console.log(changeName)
    changeName.value = '지은 이'

    return {
      book,
      checkBookTitle,
      methodBookTitle,
      authorName,
      changeName
    }
  }
}
</script>

 

 

Computed getter / setter 사용하여 처리

<template>
  <div>
    <h2>책 제목이 5글자 이상인 경우인가요?</h2>
    <h3>{{ checkBookTitle }}</h3>
    <h3>{{ checkBookTitle }}</h3>
    <h3>{{ methodBookTitle() }}</h3>
    <h3>{{ methodBookTitle() }}</h3>
    <br />
    <h2>author</h2>
    <h3>{{ authorName }}</h3>
  </div>
</template>

<script>
import { computed, reactive, ref } from 'vue'
export default {
  setup() {
    const book = reactive({
      title: 'vue 학습 책입니다.',
      author: 'test'
    })

    const checkBookTitle = computed(() => {
      console.log('computed')
      return book.title.length > 5 ? '예' : '아니오'
    })

    const methodBookTitle = () => {
      console.log('methods')
      return book.title.length > 5 ? '예' : '아니오'
    }

    const authorName = ref('락토')
    const changeName = computed({
      get() {
        console.log('get')
        return authorName.value
      },
      set(value) {
        console.log('set')
        authorName.value = value
      }
    })

    console.log(changeName.value)
    changeName.value = '지은 이'

    return {
      book,
      checkBookTitle,
      methodBookTitle,
      authorName,
      changeName
    }
  }
}
</script>

 

※ Reference 📑
 Vue Computed 공식 문서 :  https://ko.vuejs.org/guide/essentials/computed

 

Vue.js

Vue.js - The Progressive JavaScript Framework

vuejs.org

 

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

반응형

'프로그래밍 > Vue' 카테고리의 다른 글

[Vue3] onMounted  (0) 2024.05.14
Vue.js 2.0 라이프 사이클  (0) 2024.02.21
[Vue.js] Props 란  (0) 2022.06.30
구구단 게임  (0) 2020.07.13

+ Recent posts