Vue - script setup

h.Im·2024년 9월 11일

Vue 기초

목록 보기
16/28
post-thumbnail
<script setup>

은 Vue 3에서 도입된 새로운 컴포넌트 정의 방식으로, Composition API를 더 간결하게 사용할 수 있도록 만들어진 특별한 script 구문입니다. 기존에 setup() 함수를 사용하는 방법보다 더 직관적이고 간결하게 컴포넌트를 작성할 수 있게 도와줍니다.
script setup 구문 안에서 작성된 모든 코드는 자동으로 컴포넌트의 setup() 함수 내부에서 실행됩니다. 즉, 별도로 setup() 함수를 선언할 필요가 없습니다.

<template>
  <div>
    <p>{{ message }}</p>
    <button @click="count++">Count: {{ count }}</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

// 상태 정의
const message = 'Hello, Vue 3!';
const count = ref(0);
</script>

props 받기

<template>
  <p>{{ message }}</p>
</template>

<script setup>
// props는 선언만으로 자동으로 템플릿에서 사용 가능
const props = defineProps({
  message: String
});
</script>

setup 함수에서 prop을 선언하는 것 보다 간소화 된 것을 확인할 수 있습니다.

예시)emits 사용

<template>
  <button @click="emit('increment')">Increment</button>
</template>

<script setup>
// emit 이벤트 정의
const emit = defineEmits(['increment']);
</script>

0개의 댓글