Computed API
템플릿 문법은 간단히 사용하면 편리 그러나 템플릿 내의 코드가 길어지는 경우 가독성이 떨어짐.
“선언적이지 않다고 이야기한다.”
computed 안에 선언한 값을 그대로 변수처럼 사용할 수 있다.
<template>
<div>
<h2>{ { teacher.name } }</h2>
<h3>강의가 있습니까?</h3>
<p>{ { teacher.lectures.length > 0 ? '있음' : '없음' } }</p>
</div>
</template>
<script>
import { reactive, ref } from 'vue';
export default {
setup() {
const teacher = reactive({
name: '짐코딩',
lectures: ['HTML/CSS', 'Javascript', 'VUe3'],
});
return {
teacher,
};
},
};
</script>
<style></style>
위와 같은 경우 템플릿 코드 너무 복잡 여러개 사용한다고 하면 더 복잡해질 것임.
<template>
<div>
<h2>{{ teacher.name }}</h2>
<h3>강의가 있습니까?</h3>
<!-- <p>{ { teacher.lectures.length > 0 ? '있음' : '없음' \}\}</p> -->
<p>{{ hasLecture }}</p>
</div>
</template>
<script>
import { reactive, computed, ref } from 'vue';
export default {
setup() {
const teacher = reactive({
name: '짐코딩',
lectures: ['HTML/CSS', 'Javascript', 'VUe3'],
});
const hasLecture = computed(() =>
teacher.lectures.length > 0 ? '있음' : '없음',
);
return {
teacher,
hasLecture,
};
},
};
</script>
<style></style>
const hasLecture = computed(() =>
teacher.lectures.length > 0 ? '있음' : '없음',
);
위와 같이 사용하여 hasLecture를 템플릿 안에 넣을 수 있다.
메서드와의 차이점?
const existLecture = () => (teacher.lectures.length > 0 ? '있음' : '없음');
이런식으로 메서드로 만들어서 템플릿에 넣을 때
<p>{ { existLecture() \}\}</p>
이런식으로 넣어도 동작은 한다.
그러나 computed 는 계산된 값이 캐시되어지므로 성능면에서 computed를 쓰는 것이 좋다.
만약에 같은 값을 여러번 출력하면
매번 실행하면서 찍어주는 것이 아니라 캐시된 것들을 그대로 가져옴.
computed를 실행시키는 시점은 반응형 데이터가 변경되었을 때 실행됨.
computed 는 기본적으로 getter 속성임.
새 값을 할당하면 warning 을 띄워줌.
computed 에 set 쓰기
const fullName = computed({
get() {
return firstName.value + ' ' + lastName.value;
},
set(value) {
[firstName.value, lastName.value] = value.split(' ');
},
});
fullName.value = '짐 코딩';
위와 같이 setter를 만들어서 사용하면 변수까지 수정을 하여서 다시 가져올 수 있게끔 만들면 된다.