첫 프로젝트를 하면서 선임에게 배운 객체 key 동적 할당하는 코드다.
동일한 기능을 수행하는 1개의 컴포넌트를 여러군데에서 사용할 때,
사용하는 곳마다 데이터 필드값을 다르게 줄 수도 있다!
그런 상황들에 대응하기 위해 아래와 같은 코드를 적용할 수 있다.
<script>
props: {
fieldNameObj: {
// 파싱 데이터 필드 이름
type: Object,
default: () => ({}),
},
},
setup(props) {
const fieldNames = ref({
costType: 'costDivisionName',
taxation: 'taxationYn',
paymentAmount: 'supplyAmount',
surtax: 'surtax',
realPaymentAmount: 'realPaymentAmount',
reckoningList: 'reckoningList',
monthPaymentAmount: 'supplyAmount',
monthSurtax: 'surtax',
monthRealPaymentAmount: 'realPaymentAmount',
});
onMounted(() => {
fieldNames.value = { ...fieldNames.value, ...props.fieldNameObj };
- 코드 생략 -
});
}
</script>
컴포넌트에 디폴트로 지정된 fieldNames이 있는데,
해당 컴포넌트를 사용하는 곳에서 데이터 필드 이름을 다르게 내려주고 있다면
해당 데이터 필드 이름을 props로 받아와 아래와 같이 덮어씌운다.
onMounted(() => {
fieldNames.value = { ...fieldNames.value, ...props.fieldNameObj };
});
이렇게 만들어두면 나중에 데이터 필드값을 다르게 받아오더라도
아래와 같이 사용할 수 있어서 데이터 필드값을 다르게 받아오는 상황에도 대응할 수 있다.
<template>
<div>
<!-- 다른 내용들 -->
<child-component :fieldNameObj="customFieldNames" />
</div>
</template>
<script setup>
import { ref } from 'vue';
const customFieldNames = ref({
costType: 'costTypeCustomName',
taxation: 'taxationCustomName',
// 예시로 두 개의 필드 이름만 커스터마이징합니다.
});
</script>
위의 코드처럼 customFieldNames를 넘겨주면 아래 코드로 인해
병합 후 child-component의 fieldNames 객체는 넘겨준 객체로 변경되어있다.
onMounted(() => {
fieldNames.value = { ...fieldNames.value, ...props.fieldNameObj };
});
{
costType: 'costTypeCustomName',
taxation: 'taxationCustomName',
paymentAmount: 'supplyAmount',
surtax: 'surtax',
realPaymentAmount: 'realPaymentAmount',
reckoningList: 'reckoningList',
monthPaymentAmount: 'supplyAmount',
monthSurtax: 'surtax',
monthRealPaymentAmount: 'realPaymentAmount',
}
// props로 받아온 필드명이 없는 경우
fieldNames.value.costType // 출력값: costDivisionName
// props로 받아온 필드명이 있는 경우
fieldNames.value.costType // 출력값: costTypeCustomName
다양한 필드값을 대응하기 좋은 코드라고 생각된다!