Vue 3 Composition API : Script Setup & LifeCycle Hooks

2023. 8. 10. 16:19·📘 Frontend/Vue
목차
  1. Script Setup
  2. Composition API - LifeCycle Hooks

Script Setup

기존 setup()를 사용하는 것보다 가독성 측면에서 더 뛰어난 Script Setup에서의 다양한 기능들의 사용법 입니다.

변경점만 간단하게 작성합니다.


<template>
  <div>
    <p>Props value: {{ propsValue }}</p>
    <p>Injected value: {{ injectedValue }}</p>
    <p>Computed value: {{ computedValue }}</p>
    <p>Reactive value: {{ reactiveValue }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup>
import { ref, reactive, computed, toRefs, inject, defineProps, defineEmits, provide } from 'vue';

// Props
const props = defineProps({
  propsValue: String,
});

// Provide, 1: 임의 식별자 2: 전달하고자 하는 실제 값  
provide('userAge', user.age)

// Emit
const emit = defineEmits();

// Inject 1: Provide의 첫번째 파라미터
const injectedValue = inject('injectedValue');

// State
const count = ref(0);
const state = reactive({
  reactiveValue: 42,
});

// Computed
const computedValue = computed(() => count.value * 2);

// Methods
const increment = () => {
  count.value++;
  emit('incremented', count.value);
};

// Destructuring props and reactive state
const { propsValue } = toRefs(props);
const { reactiveValue } = toRefs(state);
</script>

  1. props: defineProps를 통해 부모 컴포넌트로부터 전달된 프롭스를 정의합니다.

  2. emit: defineEmits를 통해 이벤트를 발생시키는 함수를 정의하고, 이를 통해 부모 컴포넌트로 이벤트를 전달합니다.

  3. inject: inject 함수를 사용하여 부모 컴포넌트나 상위 계층에서 제공된 값을 주입받습니다.

  4. ref: ref 함수를 사용하여 반응형 변수를 생성합니다.

  5. reactive: reactive 함수를 사용하여 반응형 상태 객체를 생성합니다.

  6. computed: computed 함수를 사용하여 계산된 속성을 정의하고 사용합니다.

  7. toRefs: toRefs 함수를 사용하여 반응형 변수 또는 상태를 단순한 ref로 변환합니다.


script setup을 사용하면 이러한 항목들을 더욱 간단하게 정의하고 활용할 수 있습니다.

각 항목은 Composition API의 기능을 더 편리하게 사용하도록 도와줍니다.


Option API -> Composition API
data() {...} -> ref(), reactive()
methods: { doSmth() {...} } -> function doSmth() {...}
computed: { val() {...} } -> const val = computed()
watch: {...} -> watch(dep, (val, oldV) => {})
provide: {...} / inject: [] -> provide(key, val) / inject(key)

Composition API - LifeCycle Hooks

Option API -> Composition API
beforeCreate(), create() -> 불필요 (setuo()이 대신함)
beforeMount(), mounted() -> onBeforeMount(), onMounter()
beforeUpdate(), updated() -> onBeforeUpdate(), onUpdated()
beforeUnmount(), unmounted() -> onBeforeMount(), onUnmounted()

beforeCreate, create()

Option API와는 다르게 Composition API는 LifeCycle Hook을 컴포넌트 구성에 추가하지 않습니다.

내부적으로 Vue에서 함수를 불러오고 Setup에서 그 함수를 호출하죠.

기본적으로 setup은 beforeCreate, created가 실행되는 시점에 실행되기 때문입니다.

즉, setup 함수가 2개의 Lifecycle Hook을 자동으로 실행시켜 줍니다.


beforeCreate(), create()를 제외하고 나머지 LifyCycle 함수들은 전부 앞에 on만 붙고 사용법이 비슷합니다.

저작자표시 (새창열림)

'📘 Frontend > Vue' 카테고리의 다른 글

Vue 3 Composition API : Vuex - Actions (Asynchronous)  (1) 2023.08.13
Vue 3 Composition API : Vuex Basic & Mutation  (0) 2023.08.13
Vue 3 Composition API : Methods & Computed & Watcher  (0) 2023.08.10
Vue 3 Composition API : Reactive Object  (0) 2023.08.09
Vue 3 Composition API : Option API -> Composition API  (0) 2023.08.08
  1. Script Setup
  2. Composition API - LifeCycle Hooks
'📘 Frontend/Vue' 카테고리의 다른 글
  • Vue 3 Composition API : Vuex - Actions (Asynchronous)
  • Vue 3 Composition API : Vuex Basic & Mutation
  • Vue 3 Composition API : Methods & Computed & Watcher
  • Vue 3 Composition API : Reactive Object
신건우
신건우
조용한 개발자
  • 신건우
    우주먼지
    신건우
  • 전체
    오늘
    어제
    • 분류 전체보기 (422)
      • 📘 Frontend (71)
        • Markup (1)
        • Style Sheet (2)
        • Dart (8)
        • Javascript (12)
        • TypeScript (1)
        • Vue (36)
        • React (2)
        • Flutter (9)
      • 📘 Backend (143)
        • Java (34)
        • Concurrency (19)
        • Reflection (1)
        • Kotlin (29)
        • Python (1)
        • Spring (42)
        • Spring Cloud (5)
        • Message Broker (5)
        • Streaming (2)
        • 기능 개발 (5)
      • 💻 Server (6)
        • Linux (6)
      • ❌ Error Handling (11)
      • 📦 Database (62)
        • SQL (31)
        • NoSQL (2)
        • JPQL (9)
        • QueryDSL (12)
        • Basic (4)
        • Firebase (4)
      • ⚙️ Ops (57)
        • CS (6)
        • AWS (9)
        • Docker (8)
        • Kubernetes (13)
        • MSA (1)
        • CI & CD (20)
      • 📚 Data Architect (48)
        • Data Structure (10)
        • Algorithm (8)
        • Programmers (17)
        • BaekJoon (5)
        • CodeUp (4)
        • Design Pattern (4)
        • AI (0)
      • ⚒️ Management & Tool (8)
        • Git (7)
        • IntelliJ (1)
      • 📄 Document (10)
        • Project 설계 (6)
        • Server Migration (3)
      • 📄 책읽기 (2)
        • 시작하세요! 도커 & 쿠버네티스 (2)
      • 🎮 Game (4)
        • Stardew Vally (1)
        • Path of Exile (3)
  • 블로그 메뉴

    • 링크

      • Github
    • 공지사항

    • 인기 글

    • 태그

      Lock #Thread #Concurrency
      GStreamer #Pipeline
      React #Markdown
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    신건우
    Vue 3 Composition API : Script Setup & LifeCycle Hooks
    상단으로

    티스토리툴바

    단축키

    내 블로그

    내 블로그 - 관리자 홈 전환
    Q
    Q
    새 글 쓰기
    W
    W

    블로그 게시글

    글 수정 (권한 있는 경우)
    E
    E
    댓글 영역으로 이동
    C
    C

    모든 영역

    이 페이지의 URL 복사
    S
    S
    맨 위로 이동
    T
    T
    티스토리 홈 이동
    H
    H
    단축키 안내
    Shift + /
    ⇧ + /

    * 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.