Vue Computed

서진웅·2024년 1월 31일
post-thumbnail

template 태그 안에

	<template>
		{{ lectures.length > 0 ? '출석' : '공강' }}
    </template>

이런식으로 표현할 수 있지만 점점 코드가 복잡해지면 이러한 방식으로는 코드 가독성이 안좋아지는 단점이 있다. 이럴 때 사용하는 것 => computed property 이다

computed

	const isVisitSchool = computed(() => {
    	return lectures.length > 0 ? '출석' : '공강'
    })

computed VS method

	<template>
    	{{ isVisitShool2() }}
    </template>
    
    export default {
        function isVisitShool2() {
          return lectures.length > 0 ? '출석' : '공강'
		}		
    }

이렇게 해도 computed와 동일한 결과를 얻을 수 있다. 그러나 이 둘의 차이점은
computed는 결과가 캐싱되어 좀 더 최적화 되어 있다. computed가 다시 계산될때는 computed 안의 반응형 데이터가 변경된 경우일때만이다.

computed의 getter, setter

computed는 기본적으로 getter전용이다. getter, setter 모두 기능을 만들려면
computed안의 매개변수를 callback 함수가 아닌 객체로 넣어준다. 그 객체 안에 get(), set()함수를 작성해준다.

	import {computed, ref} from 'vue';
    
    export default {
    	setup() {
        	const firstName = ref('홍');
            const lastName = ref('길동');
            
            const fullName = computed({
            	get() {
                	return firstName.value + " " + lastName.value;
                },
                set(newValue) {
                	[firstName.value, lastName.value] = newValue.split(" ");
                }
            });
            
            fullName.value = '서 진웅';
            return {
            	firstName,
                lastName,
                fullName
            }
        }
    }

0개의 댓글