Front-end
vue composition api 에서 setup 위치에 따른 소스 비교
크레비즈
2025. 5. 28. 00:20
vue js 코딩을 하다보면 composition api 에서 setup 의 위치가 다를 경우가 있습니다.
<script lang="ts">
import { defineComponent, ref, computed, onMounted, watch } from 'vue';
import axios from 'axios';
import { Chart as ChartJS, ArcElement, Tooltip, Legend, Title } from 'chart.js';
import { Doughnut } from 'vue-chartjs';
import { getApiUrl } from '@/config/api';
ChartJS.register(ArcElement, Tooltip, Legend, Title);
export default defineComponent({
name: 'Page',
components: {
DoughnutChart: Doughnut,
},
setup() {
// 펀드 통계 데이터
const total = ref(0);
const averageReturn = ref(0);
위 코드처럼 <script> 아래에 export default 안에 있는 경우도 있고
<script setup lang="ts">
import { ref, onMounted, computed, watch, nextTick } from 'vue';
import axios from 'axios';
import { getApiUrl } from '@/config/api';
import Chart from 'chart.js/auto';
const selected = ref('전체'); // 기본값을 '전체'로 설정
// 연도 옵션 추가
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
두번째 코드처럼 <script> 태그 안에 setup 이 있는 경우가 있습니다.
이 두 코드의 가장 큰 차이는 첫번째 코드처럼 setup 이 export default 안에 들어가게 되면 정의된 defineComponent 를 import 해야하는것 뿐만 아니라
최종적으로 모든 선언들을 return 해줘야하는 점이 있습니다.
return {
authStore,
googleClientId,
loading,
error,
handleGoogleLogin,
handleGoogleError,
handleLogout,
router
}
이 코드처럼 return { ... } 으로 해줘야하는 점이 가장 큰 차이점인데
vue.js 공식 페이지에서 setup 옵션을 사용하는 가이드에 따르면
싱글 파일 컴포넌트에 컴포지션 API를 사용하는 경우, 보다 간결하고 인체공학적인 문법을 위해
<script setup>
사용을 권장합니다.
라고 되어 있습니다.
주로 참여했던 프로젝트에서는 첫번째처럼 코딩하라고 가이드를 줘서 첫번째처럼 코딩한 것이 익숙한데..
어느 프로젝트를 가든지, 그 프로젝트마다의 스타일이 있어서, 그 스타일을 잘 따라서 하면 되겠습니다.