스프레드(전개) 연산자는 반복 가능한 데이터의 형태를 풀어서 0개 이상의 key-value 쌍의 객체 형태로 확장이 가능하여, 새로운 규격을 만들거나 기존 규격을 유지할 때 유용하게 사용되는 문법이다.
사용자 selectbox를 생각해보면 쉽게 이해할 수 있다.
검색한 시/도에 따라 이용할 택배사를 선택하는 selectbox가 있고 시/도를 선택해야만 택배사 selectbox의 클릭 이벤트가 활성화 된다.
selectbox의 초기값은 아래와 같으며, 시/도를 선택하면 검색되는 택배사 리스트는 selectList 데이터에 추가된 후 보여져야 한다.
<template>
<div>
<comboBox v-model="state.combo" @select="callNewList"/>
<selectBox v-model="state.select" @click="select"/>
</div>
</template>
<script setup>
import {reactive} from 'vue'
import Api from '@/https'
const state = reactive({
combo : {},
select : [{id : null, name : '선택해주세요'}]
})
const callNewList = ({id}) => {
// api call and get results from response
const { data } = Api.get('test.search-delivery-list', id)
console.log(data) // expected : [{id : 1, name : '우체국'}, {id : 2, name : 'gs택배'}]
}
</script>
const callNewList = () => {
// api call and get results from response
const { data } = Api.get('test.search-delivery-list', id)
for(let i= 0; i < data.length; i++){
state.select.push(data[i])
}
}
// select = [{id : null, name : '선택해주세요'}, {id : 1, name : '우체국'}, {id : 2, name : 'gs택배'}]
const callNewList = () => {
// api call and get results from response
const { data } = Api.get('test.search-delivery-list', id)
state.select = [...state.select, ...data]
}
// select = [{id : null, name : '선택해주세요'}, {id : 1, name : '우체국'}, {id : 2, name : 'gs택배'}]
state.select = [...state.select, ...data]
해당 구문에서 state.select 의 return 값은 [] 배열, 배열 안 데이터는 state.select와 data 데이터를 각각 풀어서 key-value 한쌍씩으로 나열하였다.
내부에서 데이터는 state.select = [...[{id : null, name : '선택해주세요'}, ...[{id : 1, name : '우체국'}]]]
따라서 '...[]' 구문이 => {} 객체로 확장됨을 알 수 있다.
이렇듯, spread 연산자를 활용하여 기존 함수의 한계를 개선하고, 더 나은 코드를 구현해보면 좋겠다.