Vue - Computed Properties

h.Im·2024년 9월 9일
0

Vue 기초

목록 보기
25/28
post-thumbnail

템플릿 문법은 간단히 사용하면 매우 편리하나, 템플릿 표현식 내 코드가 길어질 경우 가독성이 떨어지고 유지보수가 어려워질 수 있습니다. 짧은 예시 코드를 들어 보겠습니다.

<p>강의가 존재합니까?</p>
<span>{{ teacher.lectures.length > 0 ? 'Yes' : 'No' }}</span>

이 코드를 어떻게 개선할 수 있을까요?

const hasLecture = computed(() => {
	return teacher.lectures.length > 0 ? 'Yes' : 'No'
})

위와 같은 computed를 작성 후,

<p>강의가 존재합니까?</p>
<span>{{ hasLecture }}</span>

템플릿 코드를 이렇게 수정하면 동일한 동작을 수행합니다. computed는 계산된 속성을 읽기전용 값으로 만들어 사용하는 효과가 있는데, 굳이 computed를 사용해야 하나 하는 의문을 가질 수 있습니다.

<template>
	<div>강의가 있나요?</div>
	<div>{{ hasLecture }}</div>
	<!-- 중괄호를 붙여줘야 한다는 것 외에는 차이가 없어 보이는데? -->
	<div>{{ hasLectureV2() }}</div>
</template>

<script>
import { reactive, computed } from 'vue'
export default {
	setup() {
		const teacher = reactive({
			lectures: ['c', 'c++', 'java'],
		})
		const hasLecture = computed(() =>
			teacher.lectures.length > 0 ? '있음' : '없음',
		)

		// 이런 일반 함수를 쓰는 것과 무슨 차이가 있길래?
		const hasLectureV2 = () => (teacher.lectures.length > 0 ? '있음' : '없음')

		return { teacher, hasLecture, hasLectureV2 }
	},
}
</script>

<style lang=""></style>

hasLectureV2라는 일반 함수를 만들어서, 똑같은 결과가 출력되게끔 하였는데, 사실 computed는 캐싱이라는 강력한 효과가 있습니다.

<template>
	<div>강의가 있나요?</div>
	<div>{{ hasLecture }}</div>
	<div>{{ hasLecture }}</div>
	<div>{{ hasLecture }}</div>
	<!-- hasLectureV2는 그려질 때마다 값을 새로 계산해 보는구나 -->
	<div>{{ hasLectureV2() }}</div>
	<div>{{ hasLectureV2() }}</div>
	<div>{{ hasLectureV2() }}</div>
</template>

<script>
import { reactive, computed } from 'vue'
export default {
	setup() {
		const teacher = reactive({
			lectures: ['c', 'c++', 'java'],
		})
		const hasLecture = computed(() => {
			console.log('hasLecture')
			return teacher.lectures.length > 0 ? '있음' : '없음'
		})

		const hasLectureV2 = () => {
			console.log('hasLectureV2')
			return teacher.lectures.length > 0 ? '있음' : '없음'
		}

		return { teacher, hasLecture, hasLectureV2 }
	},
}
</script>

<style lang=""></style>

콘솔 출력문을 보면 hasLecture가 한 번, hasLectureV2가 세 번 호출됩니다. 캐싱된 데이터가 다시 계산되는 시점은 반응형 데이터가 변경되었을 때 입니다.


computed는 기본적으로 읽기 전용입니다. 계산된 속성에 새로운 값을 할당하는 경우, 런타임 경고가 표시됩니다. 새로운 값을 할당할 필요가 있을 경우, 아래와 같이 게터와 세터를 만들어 사용할 수 있습니다.

const fullName = computed({
	get() {
    	...
    }
    set(newValue) {
    	...
    }
})

0개의 댓글