Vue 3의 코드 작성 방식 - 옵션 API와 컴포지션 API

목차

옵션 API

<div id="app">{{ message }}</div>

<script>
  Vue.createApp({
    data() {
      return {
        message: 'hi',
      };
    },
  }).mount('#app');
</script>

data는 인스턴스 옵션(Instance Option)이다. data가 돌려준 객체를 Vue가 반응형으로 만들어서 화면에 연결한다.

컴포지션 API

<div id="app">{{ message }}</div>

<script>
  const { createApp, ref } = Vue;

  createApp({
    setup() {
      const message = ref('hi');
      return {
        message
      };
    }
  }).mount('#app');
</script>

처음 글에는 ref를 꺼내는 줄이 빠져 있었다. CDN으로 Vue를 불러오면 ref도 전역 Vue 객체 안에 있어서 이렇게 꺼내 써야 한다.

Vue 3에서 옵션 API가 없어진 것은 아니고, 컴포지션 API가 새로 추가되었다. 컴포지션 API는 코드를 재활용하고 좀 더 깔끔하게 작성하려고 만들어졌다. Vue 개발 초보자라면 옵션 API로 먼저 개발해 보고 그다음 컴포지션 API를 쓰기를 권장한다.


script setup

.vue 파일(SFC)에서는 <script setup>을 쓰면 setup 함수와 return을 생략할 수 있다. 지금 공식 문서 예제도 대부분 이 형태로 되어 있다.

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

const message = ref('hi')
</script>

<template>
  <div>{{ message }}</div>
</template>

로직 재사용 예시 (composable)

컴포지션 API를 쓰면 상태와 로직을 함수 하나로 꺼낼 수 있다.

// useCounter.js
import { ref } from 'vue'

export function useCounter(start = 0) {
  const count = ref(start)
  const increment = () => count.value++
  return { count, increment }
}
<script setup>
import { useCounter } from './useCounter'

const a = useCounter()
const b = useCounter(10)
</script>

<template>
  <button @click="a.increment">{{ a.count }}</button>
  <button @click="b.increment">{{ b.count }}</button>
</template>

옵션 API였다면 mixin으로 빼거나 컴포넌트마다 같은 data, methods를 다시 적어야 했던 부분이다. 함수로 꺼내 두면 부를 때마다 자기만의 count를 따로 가진다.


세 예제가 정말 같은 결과를 내는지 확인

vue 3.5.13의 서버 렌더러(renderToString)로 옵션 API, 컴포지션 API, composable 예제를 HTML 문자열로 바꿔 봤다.

const { createSSRApp, ref } = require('vue')
const { renderToString } = require('vue/server-renderer')

const optionsApp = createSSRApp({
  data() { return { message: 'hi' } },
  template: `<div>{{ message }}</div>`
})

const compositionApp = createSSRApp({
  setup() {
    const message = ref('hi')
    return { message }
  },
  template: `<div>{{ message }}</div>`
})

function useCounter(start = 0) {
  const count = ref(start)
  const increment = () => count.value++
  return { count, increment }
}

const reuseApp = createSSRApp({
  setup() {
    const a = useCounter()
    const b = useCounter(10)
    a.increment(); b.increment(); b.increment()
    return { a, b }
  },
  template: `<p>{{ a.count }} / {{ b.count }}</p>`
})

;(async () => {
  console.log('옵션 API     :', await renderToString(optionsApp))
  console.log('컴포지션 API :', await renderToString(compositionApp))
  console.log('composable   :', await renderToString(reuseApp))
})()
옵션 API     : <div>hi</div>
컴포지션 API : <div>hi</div>
composable   : <p>1 / 12</p>

a는 0에서 한 번, b는 10에서 두 번 증가해서 1과 12가 나왔다. 같은 함수를 두 번 불러도 상태가 섞이지 않는다.

참고

댓글

GitHub 계정으로 로그인하면 댓글과 공감을 남길 수 있습니다.